import { Router } from 'express'

import {
  getAdminAffiliateDashConfig,
  getAdminAffiliateDashWallet,
  listAdminAffiliateDashProducts,
  matchAdminAffiliateDashSku,
  updateAdminAffiliateDashConfig,
} from '../../../services/admin/platform-config/affiliate-dash-service.js'
import { createJsonHandler } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/affiliate-dash',
  createJsonHandler(() => getAdminAffiliateDashConfig(), {
    successMessage: 'ok',
    errorMessage: '读取 affiliate-dash 配置失败',
    scope: '[admin/platform-config/affiliate-dash]',
  }),
)

router.post(
  '/affiliate-dash',
  createJsonHandler((req) => updateAdminAffiliateDashConfig(req.body as JsonRecord), {
    successMessage: 'affiliate-dash 配置已保存',
    errorMessage: '保存 affiliate-dash 配置失败',
    scope: '[admin/platform-config/affiliate-dash]',
    audit: (_req, data) => {
      const result = data as JsonRecord
      const source = result.source as JsonRecord | undefined
      const effective = result.effective as JsonRecord | undefined

      return {
        action: 'platform_affiliate_dash_config_updated',
        targetType: 'platform_config',
        targetId: 'affiliate_dash',
        data: {
          enabled: effective?.enabled !== false,
          hasAppKey: Boolean(effective?.hasAppKey),
          hasAppSecret: Boolean(effective?.hasAppSecret),
          hasCallbackSecret: Boolean(effective?.hasCallbackSecret),
          skuMappingCount: Number(
            source?.skuMapping && typeof source.skuMapping === 'object'
              ? Object.keys(source.skuMapping).length
              : 0,
          ),
        },
      }
    },
  }),
)

router.post(
  '/affiliate-dash/match',
  createJsonHandler((req) => matchAdminAffiliateDashSku(req.body as JsonRecord), {
    successMessage: 'ok',
    errorMessage: '匹配 affiliate-dash sku 失败',
    scope: '[admin/platform-config/affiliate-dash/match]',
  }),
)

router.post(
  '/affiliate-dash/products',
  createJsonHandler((req) => listAdminAffiliateDashProducts(req.body as JsonRecord), {
    successMessage: 'ok',
    errorMessage: '查询 affiliate-dash 商品失败',
    scope: '[admin/platform-config/affiliate-dash/products]',
  }),
)

router.post(
  '/affiliate-dash/wallet',
  createJsonHandler(() => getAdminAffiliateDashWallet(), {
    successMessage: 'ok',
    errorMessage: '查询 affiliate-dash 钱包失败',
    scope: '[admin/platform-config/affiliate-dash/wallet]',
  }),
)

export default router
