import { Router } from 'express'

import {
  failAdminNinetyoneOrder,
  getAdminNinetyoneOrders,
  retryAdminNinetyoneOrder,
} from '../../../services/admin/platform-config/ninetyone-service.js'
import type { AdminEntityRouteParams } from '../../../types/admin/route-inputs.js'
import { createJsonHandler } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/ninetyone/orders',
  createJsonHandler((req) => getAdminNinetyoneOrders(req.query), {
    successMessage: 'ok',
    errorMessage: '读取 91卡券订单失败',
    scope: '[admin/platform-config/ninetyone/orders]',
  }),
)

router.post(
  '/ninetyone/orders/:id/retry',
  createJsonHandler(
    (req) => retryAdminNinetyoneOrder(String((req.params as AdminEntityRouteParams).id || '')),
    {
      successMessage: '91卡券订单已重试',
      errorMessage: '重试 91卡券订单失败',
      scope: '[admin/platform-config/ninetyone/orders/:id/retry]',
      audit: (_req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_ninetyone_order_retried',
          targetType: 'order',
          targetId: String(result.orderId || '').trim(),
          data: {
            orderNo: String(result.orderNo || '').trim(),
            taskCount: Number(result.taskCount || 0),
          },
        }
      },
    },
  ),
)

router.post(
  '/ninetyone/orders/:id/fail',
  createJsonHandler(
    (req) =>
      failAdminNinetyoneOrder(
        String((req.params as AdminEntityRouteParams).id || ''),
        req.body as { reason?: string },
      ),
    {
      successMessage: '91卡券订单已标记失败',
      errorMessage: '标记 91卡券订单失败',
      scope: '[admin/platform-config/ninetyone/orders/:id/fail]',
      audit: (req, data) => {
        const result = data as JsonRecord
        return {
          action: 'platform_ninetyone_order_failed',
          targetType: 'order',
          targetId: String(result.orderId || '').trim(),
          data: {
            orderNo: String(result.orderNo || '').trim(),
            reason: String((req.body as { reason?: string }).reason || '').trim(),
          },
        }
      },
    },
  ),
)

export default router
