import { Router } from 'express'

import { getAdminOrderDetail, getAdminOrders } from '../../services/admin/admin-read-service.js'
import { resendAdminOrderKuaishouIndustryVoucherCodes } from '../../services/admin/write/kuaishou-cloud-actions.js'
import { createJsonHandler, requireAdminRoles } from './session.js'
import type { AdminOrderRouteParams, AdminOrderRouteQuery } from '../../types/admin/route-inputs.js'

const router = Router()

router.use('/orders', requireAdminRoles(['admin', 'operator', 'support']))

router.get(
  '/orders',
  createJsonHandler((req) => getAdminOrders(req.query as AdminOrderRouteQuery), {
    successMessage: 'ok',
    errorMessage: '读取订单列表失败',
    scope: '[admin/orders]',
  }),
)

router.get(
  '/orders/:orderId',
  createJsonHandler(
    (req) =>
      getAdminOrderDetail(
        String((req.params as AdminOrderRouteParams).orderId || ''),
        req.adminSession || null,
      ),
    {
      successMessage: 'ok',
      errorMessage: '读取订单详情失败',
      scope: '[admin/orders/:orderId]',
    },
  ),
)

router.post(
  '/orders/:orderId/kuaishou-industry/resend-code',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      resendAdminOrderKuaishouIndustryVoucherCodes(
        String((req.params as AdminOrderRouteParams).orderId || ''),
        req.adminSession || null,
      ),
    {
      successMessage: '电子凭证发码回调已重发',
      errorMessage: '重发电子凭证发码回调失败',
      scope: '[admin/orders/:orderId/kuaishou-industry/resend-code]',
      audit: (req, data) => ({
        action: 'order_kuaishou_industry_resend_code',
        targetType: 'order',
        targetId: String((req.params as AdminOrderRouteParams).orderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
