import { Router } from 'express'

import {
  closeAdminManualRedeemSession,
  closeAdminManualRedeemTask,
  confirmAdminManualRedeemRole,
  createAdminManualRedeemSession,
  createAdminManualRedeemTask,
  getAdminManualRedeemDetail,
  getAdminManualRedeemSessionSummary,
  reloadAdminManualRedeemSession,
  redeemAdminManualRedeemTask,
} from '../../services/admin/admin-manual-redeem-service.js'
import { getAdminInventorySkuSuggestions } from '../../services/admin/admin-read-service.js'
import { createJsonHandler, requireAdminRoles } from './shared.js'
import type {
  AdminInventorySkuSuggestionRouteQuery,
  AdminManualRedeemCreateRouteBody,
  AdminManualRedeemRouteParams,
} from '../../types/admin-route-inputs.js'

type AdminManualRedeemSessionRouteBody = {
  loginType?: string
  forceRecreate?: boolean
}

type AdminManualRedeemMutationResult = {
  task?: {
    taskId?: number
    taskNo?: string
    status?: string
    deliveryStatus?: string
  }
  manualRequest?: { proofValue?: string }
  order?: { platformOrderId?: string }
  orderItem?: { skuCode?: string }
}

const router = Router()

router.use('/manual-redeem', requireAdminRoles(['admin', 'operator', 'support']))

router.get('/manual-redeem/sku-suggestions', createJsonHandler(
  (req) => getAdminInventorySkuSuggestions(
    req.query as AdminInventorySkuSuggestionRouteQuery,
    req.adminSession || null,
  ),
  {
    successMessage: 'ok',
    errorMessage: '读取人工兑换 SKU 建议失败',
    scope: '[admin/manual-redeem/sku-suggestions]',
  },
))

router.post('/manual-redeem', createJsonHandler(
  (req) => createAdminManualRedeemTask(
    req.body as AdminManualRedeemCreateRouteBody,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换任务已创建',
    errorMessage: '创建人工兑换任务失败',
    scope: '[admin/manual-redeem]',
    audit: (req, data) => {
      const result = data as AdminManualRedeemMutationResult
      return {
        action: 'manual_redeem_created',
        targetType: 'task',
        targetId: String(result.task?.taskId || ''),
        data: {
          taskId: result.task?.taskId,
          taskNo: result.task?.taskNo,
          proofValue: result.manualRequest?.proofValue || result.order?.platformOrderId || '',
          skuCode: result.orderItem?.skuCode || '',
        },
      }
    },
  },
))

router.get('/manual-redeem/:taskId', createJsonHandler(
  (req) => getAdminManualRedeemDetail(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: 'ok',
    errorMessage: '读取人工兑换详情失败',
    scope: '[admin/manual-redeem/:taskId]',
  },
))

router.post('/manual-redeem/:taskId/session', createJsonHandler(
  (req) => createAdminManualRedeemSession(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.body as AdminManualRedeemSessionRouteBody,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换登录会话已创建',
    errorMessage: '创建人工兑换登录会话失败',
    scope: '[admin/manual-redeem/:taskId/session]',
  },
))

router.get('/manual-redeem/:taskId/session/summary', createJsonHandler(
  (req) => getAdminManualRedeemSessionSummary(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: 'ok',
    errorMessage: '读取人工兑换会话摘要失败',
    scope: '[admin/manual-redeem/:taskId/session/summary]',
  },
))

router.post('/manual-redeem/:taskId/session/refresh', createJsonHandler(
  (req) => reloadAdminManualRedeemSession(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换会话已刷新',
    errorMessage: '刷新人工兑换会话失败',
    scope: '[admin/manual-redeem/:taskId/session/refresh]',
  },
))

router.delete('/manual-redeem/:taskId/session', createJsonHandler(
  (req) => closeAdminManualRedeemSession(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换会话已关闭',
    errorMessage: '关闭人工兑换会话失败',
    scope: '[admin/manual-redeem/:taskId/session]',
  },
))

router.post('/manual-redeem/:taskId/confirm-role', createJsonHandler(
  (req) => confirmAdminManualRedeemRole(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: '角色已确认',
    errorMessage: '确认人工兑换角色失败',
    scope: '[admin/manual-redeem/:taskId/confirm-role]',
    audit: (req, data) => {
      const result = data as AdminManualRedeemMutationResult
      return {
        action: 'manual_redeem_role_confirmed',
        targetType: 'task',
        targetId: String(result.task?.taskId || ''),
        data: {
          taskId: result.task?.taskId,
          taskNo: result.task?.taskNo,
          status: result.task?.status,
        },
      }
    },
  },
))

router.post('/manual-redeem/:taskId/redeem', createJsonHandler(
  (req) => redeemAdminManualRedeemTask(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换任务已启动',
    errorMessage: '执行人工兑换失败',
    scope: '[admin/manual-redeem/:taskId/redeem]',
    audit: (req, data) => {
      const result = data as AdminManualRedeemMutationResult
      return {
        action: 'manual_redeem_started',
        targetType: 'task',
        targetId: String(result.task?.taskId || ''),
        data: {
          taskId: result.task?.taskId,
          taskNo: result.task?.taskNo,
          status: result.task?.status,
          deliveryStatus: result.task?.deliveryStatus,
        },
      }
    },
  },
))

router.post('/manual-redeem/:taskId/close', createJsonHandler(
  (req) => closeAdminManualRedeemTask(
    (req.params as AdminManualRedeemRouteParams).taskId,
    req.adminSession || null,
  ),
  {
    successMessage: '人工兑换任务已关闭',
    errorMessage: '关闭人工兑换任务失败',
    scope: '[admin/manual-redeem/:taskId/close]',
    audit: (req, data) => {
      const result = data as AdminManualRedeemMutationResult
      return {
        action: 'manual_redeem_closed',
        targetType: 'task',
        targetId: String(result.task?.taskId || ''),
        data: {
          taskId: result.task?.taskId,
          taskNo: result.task?.taskNo,
          status: result.task?.status,
        },
      }
    },
  },
))

export default router
