import { Router } from 'express'

import {
  buildOpen91QueryMock,
  createAffiliateDashMockClaim,
  createFeifeiMockClaim,
  createKuaishouIndustryVoucherMockData,
  createLewanMockClaim,
  getDevMockStatus,
  isDevMockEnabled,
} from '../../services/dev-mock/dev-mock-service.js'
import { createHttpError } from '../../utils/http.js'
import { createJsonHandler, requireAdminRoles } from './session.js'

const router = Router()

function requireDevMockEnabled() {
  return (_req: unknown, _res: unknown, next: (error?: unknown) => void) => {
    if (!isDevMockEnabled()) {
      next(
        createHttpError('开发 Mock 仅在非 production 环境可用（或设置 ENABLE_DEV_MOCK=1）', {
          statusCode: 403,
          errorCode: 'dev_mock_disabled',
        }),
      )
      return
    }
    next()
  }
}

router.get(
  '/dev-mock/status',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => getDevMockStatus(), {
    successMessage: 'ok',
    errorMessage: '读取 Mock 状态失败',
    scope: '[admin/dev-mock/status]',
  }),
)

router.use('/dev-mock', requireAdminRoles(['admin', 'operator']), requireDevMockEnabled())

router.post(
  '/dev-mock/lewan',
  createJsonHandler((req) => createLewanMockClaim(req.body || {}), {
    successMessage: 'lewan mock 已生成',
    errorMessage: '生成 lewan mock 失败',
    scope: '[admin/dev-mock/lewan]',
    audit: (_req, data) => ({
      action: 'dev_mock_create_lewan',
      targetType: 'dev_mock',
      targetId: String((data as { orderNo?: string })?.orderNo || ''),
      data: {
        platform: 'lewan',
        orderNo: (data as { orderNo?: string })?.orderNo,
        step: (data as { step?: string })?.step,
      },
    }),
  }),
)

router.post(
  '/dev-mock/feifei',
  createJsonHandler((req) => createFeifeiMockClaim(req.body || {}), {
    successMessage: 'feifei mock 已生成',
    errorMessage: '生成 feifei mock 失败',
    scope: '[admin/dev-mock/feifei]',
    audit: (_req, data) => ({
      action: 'dev_mock_create_feifei',
      targetType: 'dev_mock',
      targetId: String((data as { orderNo?: string })?.orderNo || ''),
      data: {
        platform: 'feifei',
        orderNo: (data as { orderNo?: string })?.orderNo,
        step: (data as { step?: string })?.step,
      },
    }),
  }),
)

router.post(
  '/dev-mock/affiliate-dash',
  createJsonHandler((req) => createAffiliateDashMockClaim(req.body || {}), {
    successMessage: 'affiliate-dash mock 已生成',
    errorMessage: '生成 affiliate-dash mock 失败',
    scope: '[admin/dev-mock/affiliate-dash]',
    audit: (_req, data) => ({
      action: 'dev_mock_create_affiliate_dash',
      targetType: 'dev_mock',
      targetId: String((data as { orderNo?: string })?.orderNo || ''),
      data: {
        platform: 'affiliate_dash',
        orderNo: (data as { orderNo?: string })?.orderNo,
        step: (data as { step?: string })?.step,
      },
    }),
  }),
)

router.post(
  '/dev-mock/kuaishou-industry/vouchers',
  createJsonHandler((req) => createKuaishouIndustryVoucherMockData(req.body || {}), {
    successMessage: '快手电子凭证 Mock 已生成',
    errorMessage: '生成快手电子凭证 Mock 失败',
    scope: '[admin/dev-mock/kuaishou-industry/vouchers]',
    audit: (_req, data) => ({
      action: 'dev_mock_create_kuaishou_industry_vouchers',
      targetType: 'dev_mock',
      targetId: String((data as { sellerId?: string })?.sellerId || ''),
      data: {
        createdCount: (data as { createdCount?: number })?.createdCount || 0,
      },
    }),
  }),
)

router.post(
  '/dev-mock/open91/query',
  createJsonHandler((req) => buildOpen91QueryMock(req.body || {}), {
    successMessage: '91 查单 mock 已生成',
    errorMessage: '生成 91 查单 mock 失败',
    scope: '[admin/dev-mock/open91/query]',
  }),
)

export default router
