import { Router } from 'express'

import {
  exchangeAdminKuaishouIndustryAuthorizationCode,
  getAdminKuaishouIndustrySourceConfig,
  refreshAdminKuaishouIndustryAccessToken,
  updateAdminKuaishouIndustrySourceConfig,
} from '../../../services/admin/platform-config/kuaishou-industry-service.js'
import type {
  AdminKuaishouIndustryAuthorizationCodeRouteBody,
  AdminKuaishouIndustrySourceConfigRouteBody,
} from '../../../types/admin/route-inputs.js'
import { createJsonHandler, requireAdminRoles } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/kuaishou-industry-source',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => getAdminKuaishouIndustrySourceConfig(), {
    successMessage: 'ok',
    errorMessage: '读取快手行业电子凭证配置失败',
    scope: '[admin/platform-config/kuaishou-industry-source]',
  }),
)

router.post(
  '/kuaishou-industry-source',
  requireAdminRoles(['admin']),
  createJsonHandler(
    (req) =>
      updateAdminKuaishouIndustrySourceConfig(
        req.body as AdminKuaishouIndustrySourceConfigRouteBody,
      ),
    {
      successMessage: '快手行业电子凭证配置已保存',
      errorMessage: '保存快手行业电子凭证配置失败',
      scope: '[admin/platform-config/kuaishou-industry-source]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_kuaishou_industry_source_updated',
          targetType: 'platform_config',
          targetId: 'kuaishou_industry_source',
          data: {
            filePath: String(result.filePath || '').trim(),
            enabled: Boolean(result.source?.enabled),
            shopCount: Array.isArray(result.source?.shops) ? result.source.shops.length : 0,
            hasAccessToken: Boolean(result.source?.hasAccessToken),
            hasRefreshToken: Boolean(result.source?.hasRefreshToken),
            accessTokenStatus: String(result.source?.accessTokenStatus || '').trim(),
          },
        }
      },
    },
  ),
)

router.post(
  '/kuaishou-industry-source/refresh-token',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => refreshAdminKuaishouIndustryAccessToken(req.body as JsonRecord), {
    successMessage: '快手行业电子凭证 accessToken 已刷新',
    errorMessage: '刷新快手行业电子凭证 accessToken 失败',
    scope: '[admin/platform-config/kuaishou-industry-source/refresh-token]',
    audit: (_req, data) => {
      const result = data as JsonRecord
      return {
        action: 'platform_kuaishou_industry_access_token_refreshed',
        targetType: 'platform_config',
        targetId: 'kuaishou_industry_source',
        data: {
          refreshed: Boolean(result.refreshed),
          sellerId: String(result.shop?.sellerId || '').trim(),
          accessTokenExpiresAt: String(result.shop?.accessTokenExpiresAt || '').trim(),
          accessTokenStatus: String(result.shop?.accessTokenStatus || '').trim(),
        },
      }
    },
  }),
)

router.post(
  '/kuaishou-industry-source/exchange-code',
  requireAdminRoles(['admin']),
  createJsonHandler(
    (req) =>
      exchangeAdminKuaishouIndustryAuthorizationCode(
        req.body as AdminKuaishouIndustryAuthorizationCodeRouteBody,
      ),
    {
      successMessage: '快手行业电子凭证授权 token 已保存',
      errorMessage: '换取快手行业电子凭证授权 token 失败',
      scope: '[admin/platform-config/kuaishou-industry-source/exchange-code]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_kuaishou_industry_authorization_code_exchanged',
          targetType: 'platform_config',
          targetId: 'kuaishou_industry_source',
          data: {
            refreshed: Boolean(result.refreshed),
            sellerId: String(result.shop?.sellerId || '').trim(),
            accessTokenExpiresAt: String(result.shop?.accessTokenExpiresAt || '').trim(),
            refreshTokenExpiresAt: String(result.shop?.refreshTokenExpiresAt || '').trim(),
            accessTokenStatus: String(result.shop?.accessTokenStatus || '').trim(),
          },
        }
      },
    },
  ),
)

export default router
