import { Router } from 'express'

import {
  appointAdminCloudtentaclesVirtualNumber,
  backAdminCloudtentaclesVirtualNumber,
  buyAdminCloudtentaclesSku,
  deleteAdminCloudtentaclesSource,
  fetchAdminCloudtentaclesVirtualNumberCode,
  generateAdminCloudtentaclesLoginCode,
  getAdminCloudtentaclesOverrideRules,
  getAdminCloudtentaclesAsset,
  getAdminCloudtentaclesBindUrl,
  getAdminCloudtentaclesCategories,
  getAdminCloudtentaclesKnapsack,
  getAdminCloudtentaclesSkuList,
  listAdminCloudtentaclesSources,
  listAdminCloudtentaclesVirtualNumbers,
  runAdminCloudtentaclesFullFlow,
  sendAdminCloudtentaclesSmsCode,
  testAdminCloudtentaclesLogin,
  updateAdminCloudtentaclesOverrideRules,
  updateAdminCloudtentaclesSourceConfig,
  useAdminCloudtentaclesSku,
  validateAdminCloudtentaclesSession,
  verifyAdminCloudtentaclesLoginCode,
} from '../../../services/admin/platform-config/cloudtentacles/index.js'
import type {
  AdminCloudtentaclesCatalogQueryRouteBody,
  AdminCloudtentaclesFullFlowRouteBody,
  AdminCloudtentaclesOverrideRuleConfigRouteBody,
  AdminCloudtentaclesSendSmsCodeRouteBody,
  AdminCloudtentaclesSkuBuyRouteBody,
  AdminCloudtentaclesSkuUseRouteBody,
  AdminCloudtentaclesSourceConfigRouteBody,
  AdminCloudtentaclesTestLoginRouteBody,
  AdminCloudtentaclesValidateSessionRouteBody,
  AdminCloudtentaclesVirtualNumberRouteBody,
} from '../../../types/admin/route-inputs.js'
import { createJsonHandler } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/cloudtentacles-source',
  createJsonHandler(() => listAdminCloudtentaclesSources(), {
    successMessage: 'ok',
    errorMessage: '读取 cloudtentacles 履约平台配置失败',
    scope: '[admin/platform-config/cloudtentacles-source]',
  }),
)

router.delete(
  '/cloudtentacles-source/:sourceKey',
  createJsonHandler(
    (req) => deleteAdminCloudtentaclesSource(String(req.params.sourceKey || '').trim()),
    {
      successMessage: 'cloudtentacles 履约平台配置已删除',
      errorMessage: '删除 cloudtentacles 履约平台配置失败',
      scope: '[admin/platform-config/cloudtentacles-source/:sourceKey]',
      audit: (req) => ({
        action: 'platform_cloudtentacles_source_deleted',
        targetType: 'platform_config',
        targetId: String(req.params.sourceKey || '').trim(),
        data: {},
      }),
    },
  ),
)

router.post(
  '/cloudtentacles-source',
  createJsonHandler(
    (req) =>
      updateAdminCloudtentaclesSourceConfig(req.body as AdminCloudtentaclesSourceConfigRouteBody),
    {
      successMessage: 'cloudtentacles 履约平台配置已保存',
      errorMessage: '保存 cloudtentacles 履约平台配置失败',
      scope: '[admin/platform-config/cloudtentacles-source]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_cloudtentacles_source_updated',
          targetType: 'platform_config',
          targetId: 'cloudtentacles_source',
          data: {
            filePath: String(result.filePath || '').trim(),
            username: String(result.source?.username || '').trim(),
            enabled: Boolean(result.source?.enabled),
          },
        }
      },
    },
  ),
)

router.get(
  '/cloudtentacles/override-rules',
  createJsonHandler(() => getAdminCloudtentaclesOverrideRules(), {
    successMessage: 'ok',
    errorMessage: '读取 cloudtentacles 覆盖规则失败',
    scope: '[admin/platform-config/cloudtentacles/override-rules]',
  }),
)

router.post(
  '/cloudtentacles/override-rules',
  createJsonHandler(
    (req) =>
      updateAdminCloudtentaclesOverrideRules(
        req.body as AdminCloudtentaclesOverrideRuleConfigRouteBody,
      ),
    {
      successMessage: 'cloudtentacles 覆盖规则已保存',
      errorMessage: '保存 cloudtentacles 覆盖规则失败',
      scope: '[admin/platform-config/cloudtentacles/override-rules]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_cloudtentacles_override_rules_updated',
          targetType: 'platform_config',
          targetId: 'cloudtentacles_override_rules',
          data: {
            filePath: String(result.filePath || '').trim(),
            enabled: result.enabled !== false,
            ruleCount: Array.isArray(result.rules) ? result.rules.length : 0,
          },
        }
      },
    },
  ),
)

router.post(
  '/cloudtentacles/send-sms-code',
  createJsonHandler(
    (req) => sendAdminCloudtentaclesSmsCode(req.body as AdminCloudtentaclesSendSmsCodeRouteBody),
    {
      successMessage: 'cloudtentacles 短信验证码已发送',
      errorMessage: 'cloudtentacles 发送短信验证码失败',
      scope: '[admin/platform-config/cloudtentacles/send-sms-code]',
      audit: (req, data) => {
        const body = req.body as AdminCloudtentaclesSendSmsCodeRouteBody
        const result = data as JsonRecord
        return {
          action: 'platform_cloudtentacles_send_sms_code',
          targetType: 'platform_config',
          targetId: String(result.username || body.username || '').trim() || 'cloudtentacles',
          data: {
            baseUrl: result.baseUrl || String(body.baseUrl || '').trim(),
            phoneMasked: result.phoneMasked || '',
          },
        }
      },
    },
  ),
)

router.post(
  '/cloudtentacles/test-login',
  createJsonHandler(
    (req) => testAdminCloudtentaclesLogin(req.body as AdminCloudtentaclesTestLoginRouteBody),
    {
      successMessage: 'cloudtentacles 登录测试成功',
      errorMessage: 'cloudtentacles 登录测试失败',
      scope: '[admin/platform-config/cloudtentacles/test-login]',
      audit: (req, data) => {
        const body = req.body as AdminCloudtentaclesTestLoginRouteBody
        const result = data as JsonRecord
        return {
          action: 'platform_cloudtentacles_test_login',
          targetType: 'platform_config',
          targetId: String(result.username || body.username || '').trim() || 'cloudtentacles',
          data: {
            baseUrl: result.baseUrl || String(body.baseUrl || '').trim(),
            permissionCount: Number(result.session?.permissionCount || 0),
          },
        }
      },
    },
  ),
)

router.post(
  '/cloudtentacles/validate-session',
  createJsonHandler(
    (req) =>
      validateAdminCloudtentaclesSession(req.body as AdminCloudtentaclesValidateSessionRouteBody),
    {
      successMessage: 'cloudtentacles 会话校验成功',
      errorMessage: 'cloudtentacles 会话校验失败',
      scope: '[admin/platform-config/cloudtentacles/validate-session]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_cloudtentacles_validate_session',
          targetType: 'platform_config',
          targetId: 'cloudtentacles_session',
          data: {
            baseUrl: String(result.baseUrl || '').trim(),
            permissionCount: Number(result.session?.permissionCount || 0),
          },
        }
      },
    },
  ),
)

router.post(
  '/cloudtentacles/asset',
  createJsonHandler(
    (req) => getAdminCloudtentaclesAsset(req.body as AdminCloudtentaclesCatalogQueryRouteBody),
    {
      successMessage: 'cloudtentacles 余额查询成功',
      errorMessage: 'cloudtentacles 余额查询失败',
      scope: '[admin/platform-config/cloudtentacles/asset]',
    },
  ),
)

router.post(
  '/cloudtentacles/categories',
  createJsonHandler(
    (req) => getAdminCloudtentaclesCategories(req.body as AdminCloudtentaclesCatalogQueryRouteBody),
    {
      successMessage: 'cloudtentacles 分类查询成功',
      errorMessage: 'cloudtentacles 分类查询失败',
      scope: '[admin/platform-config/cloudtentacles/categories]',
    },
  ),
)

router.post(
  '/cloudtentacles/sku/list',
  createJsonHandler(
    (req) => getAdminCloudtentaclesSkuList(req.body as AdminCloudtentaclesCatalogQueryRouteBody),
    {
      successMessage: 'cloudtentacles SKU 列表查询成功',
      errorMessage: 'cloudtentacles SKU 列表查询失败',
      scope: '[admin/platform-config/cloudtentacles/sku/list]',
    },
  ),
)

router.post(
  '/cloudtentacles/sku/buy',
  createJsonHandler(
    (req) => buyAdminCloudtentaclesSku(req.body as AdminCloudtentaclesSkuBuyRouteBody),
    {
      successMessage: 'cloudtentacles SKU 购买成功',
      errorMessage: 'cloudtentacles SKU 购买失败',
      scope: '[admin/platform-config/cloudtentacles/sku/buy]',
    },
  ),
)

router.post(
  '/cloudtentacles/sku/use',
  createJsonHandler(
    (req) => useAdminCloudtentaclesSku(req.body as AdminCloudtentaclesSkuUseRouteBody),
    {
      successMessage: 'cloudtentacles 发货成功',
      errorMessage: 'cloudtentacles 发货失败',
      scope: '[admin/platform-config/cloudtentacles/sku/use]',
    },
  ),
)

router.post(
  '/cloudtentacles/knapsack',
  createJsonHandler(
    (req) => getAdminCloudtentaclesKnapsack(req.body as AdminCloudtentaclesCatalogQueryRouteBody),
    {
      successMessage: 'cloudtentacles 背包查询成功',
      errorMessage: 'cloudtentacles 背包查询失败',
      scope: '[admin/platform-config/cloudtentacles/knapsack]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/list',
  createJsonHandler(
    (req) =>
      listAdminCloudtentaclesVirtualNumbers(req.body as AdminCloudtentaclesVirtualNumberRouteBody),
    {
      successMessage: 'cloudtentacles 虚拟号列表查询成功',
      errorMessage: 'cloudtentacles 虚拟号列表查询失败',
      scope: '[admin/platform-config/cloudtentacles/vn/list]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/appoint',
  createJsonHandler(
    (req) =>
      appointAdminCloudtentaclesVirtualNumber(
        req.body as AdminCloudtentaclesVirtualNumberRouteBody,
      ),
    {
      successMessage: 'cloudtentacles 虚拟号申请成功',
      errorMessage: 'cloudtentacles 虚拟号申请失败',
      scope: '[admin/platform-config/cloudtentacles/vn/appoint]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/generate-login-code',
  createJsonHandler(
    (req) =>
      generateAdminCloudtentaclesLoginCode(req.body as AdminCloudtentaclesVirtualNumberRouteBody),
    {
      successMessage: 'cloudtentacles 登录码生成成功',
      errorMessage: 'cloudtentacles 登录码生成失败',
      scope: '[admin/platform-config/cloudtentacles/vn/generate-login-code]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/fetch-code',
  createJsonHandler(
    (req) =>
      fetchAdminCloudtentaclesVirtualNumberCode(
        req.body as AdminCloudtentaclesVirtualNumberRouteBody,
      ),
    {
      successMessage: 'cloudtentacles 验证码获取成功',
      errorMessage: 'cloudtentacles 验证码获取失败',
      scope: '[admin/platform-config/cloudtentacles/vn/fetch-code]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/verify-code',
  createJsonHandler(
    (req) =>
      verifyAdminCloudtentaclesLoginCode(req.body as AdminCloudtentaclesVirtualNumberRouteBody),
    {
      successMessage: 'cloudtentacles 登录码校验成功',
      errorMessage: 'cloudtentacles 登录码校验失败',
      scope: '[admin/platform-config/cloudtentacles/vn/verify-code]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/bind-url',
  createJsonHandler(
    (req) => getAdminCloudtentaclesBindUrl(req.body as AdminCloudtentaclesVirtualNumberRouteBody),
    {
      successMessage: 'cloudtentacles 兑换链接获取成功',
      errorMessage: 'cloudtentacles 兑换链接获取失败',
      scope: '[admin/platform-config/cloudtentacles/vn/bind-url]',
    },
  ),
)

router.post(
  '/cloudtentacles/vn/back',
  createJsonHandler(
    (req) =>
      backAdminCloudtentaclesVirtualNumber(req.body as AdminCloudtentaclesVirtualNumberRouteBody),
    {
      successMessage: 'cloudtentacles 号码退还成功',
      errorMessage: 'cloudtentacles 号码退还失败',
      scope: '[admin/platform-config/cloudtentacles/vn/back]',
    },
  ),
)

router.post(
  '/cloudtentacles/debug/full-flow',
  createJsonHandler(
    (req) => runAdminCloudtentaclesFullFlow(req.body as AdminCloudtentaclesFullFlowRouteBody),
    {
      successMessage: 'cloudtentacles 完整调试流程执行成功',
      errorMessage: 'cloudtentacles 完整调试流程执行失败',
      scope: '[admin/platform-config/cloudtentacles/debug/full-flow]',
    },
  ),
)

export default router
