import type { Request } from 'express'
import { Router } from 'express'

import { getAdminTaskDetail, getAdminTasks } from '../../services/admin/admin-read-service.js'
import { closeAdminTask } from '../../services/admin/write/task-actions.js'
import {
  consumeAdminTaskKuaishouIndustryVoucher,
  dispatchAdminTaskKuaishouCloudFulfillment,
  prepareAdminTaskKuaishouCloudFulfillment,
  rebindAdminTaskKuaishouCloudRole,
  refreshAdminTaskKuaishouCloudRoleInfo,
  resendAdminTaskKuaishouIndustryVoucherCode,
  returnNumberAdminTaskKuaishouCloudFulfillment,
} from '../../services/admin/write/kuaishou-cloud-actions.js'
import { createJsonHandler, requireAdminRoles } from './session.js'
import type {
  AdminTaskKuaishouIndustryConsumeRouteBody,
  AdminTaskRouteParams,
  AdminTaskRouteQuery,
} from '../../types/admin/route-inputs.js'
import type { AdminTaskActionResponse } from '../../types/admin/write-models.js'

const router = Router()

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

function getTaskId(req: Request): string {
  return String((req.params as AdminTaskRouteParams).taskId || '')
}

router.get(
  '/tasks',
  createJsonHandler(
    (req) => getAdminTasks(req.query as AdminTaskRouteQuery, req.adminSession || null),
    {
      successMessage: 'ok',
      errorMessage: '读取任务列表失败',
      scope: '[admin/tasks]',
    },
  ),
)

router.get(
  '/tasks/:taskId',
  createJsonHandler((req) => getAdminTaskDetail(getTaskId(req), req.adminSession || null), {
    successMessage: 'ok',
    errorMessage: '读取任务详情失败',
    scope: '[admin/tasks/:taskId]',
  }),
)

router.post(
  '/tasks/:taskId/close',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => closeAdminTask(getTaskId(req), req.adminSession || null), {
    successMessage: '任务已关闭',
    errorMessage: '关闭任务失败',
    scope: '[admin/tasks/:taskId/close]',
    audit: (req, data) => buildTaskAudit('task_closed', req, data),
  }),
)

router.post(
  '/tasks/:taskId/kuaishou-cloud/prepare',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => prepareAdminTaskKuaishouCloudFulfillment(getTaskId(req), req.adminSession || null),
    {
      successMessage: '绑定资源已准备完成',
      errorMessage: '准备绑定资源失败',
      scope: '[admin/tasks/:taskId/kuaishou-cloud/prepare]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_cloud_prepare', req, data),
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-cloud/refresh-role-info',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) => refreshAdminTaskKuaishouCloudRoleInfo(getTaskId(req), req.adminSession || null),
    {
      successMessage: '角色信息已刷新',
      errorMessage: '刷新角色信息失败',
      scope: '[admin/tasks/:taskId/kuaishou-cloud/refresh-role-info]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_cloud_role_info_refreshed', req, data),
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-cloud/rebind-role',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) => rebindAdminTaskKuaishouCloudRole(getTaskId(req), req.adminSession || null),
    {
      // 旧号已回收时会自动跳过退号并新取号出链
      successMessage: '换绑完成：已生成新的绑定链接（原领取链接可继续使用）',
      errorMessage: '换绑角色失败',
      scope: '[admin/tasks/:taskId/kuaishou-cloud/rebind-role]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_cloud_rebind_role', req, data),
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-cloud/dispatch',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => dispatchAdminTaskKuaishouCloudFulfillment(getTaskId(req), req.adminSession || null),
    {
      successMessage: '已完成绑定确认并发货',
      errorMessage: '执行发货失败',
      scope: '[admin/tasks/:taskId/kuaishou-cloud/dispatch]',
      audit: (req, data) => {
        const result = data as AdminTaskActionResponse

        return {
          action: 'task_kuaishou_cloud_dispatch',
          targetType: 'task',
          targetId: String(getTaskId(req)),
          data: {
            taskId: result.task.taskId,
            taskNo: result.task.taskNo,
            status: result.task.status,
            deliveryStatus: result.task.deliveryStatus,
          },
        }
      },
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-cloud/return-number',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      returnNumberAdminTaskKuaishouCloudFulfillment(getTaskId(req), req.adminSession || null),
    {
      successMessage: '号码已退还',
      errorMessage: '退还号码失败',
      scope: '[admin/tasks/:taskId/kuaishou-cloud/return-number]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_cloud_return_number', req, data),
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-industry/resend-code',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) => resendAdminTaskKuaishouIndustryVoucherCode(getTaskId(req), req.adminSession || null),
    {
      successMessage: '电子凭证发码回调已重发',
      errorMessage: '重发电子凭证发码回调失败',
      scope: '[admin/tasks/:taskId/kuaishou-industry/resend-code]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_industry_resend_code', req, data),
    },
  ),
)

router.post(
  '/tasks/:taskId/kuaishou-industry/consume',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      consumeAdminTaskKuaishouIndustryVoucher(
        getTaskId(req),
        req.body as AdminTaskKuaishouIndustryConsumeRouteBody,
        req.adminSession || null,
      ),
    {
      successMessage: '电子凭证已执行核销',
      errorMessage: '执行电子凭证核销失败',
      scope: '[admin/tasks/:taskId/kuaishou-industry/consume]',
      audit: (req, data) => buildTaskAudit('task_kuaishou_industry_consume', req, data),
    },
  ),
)

function buildTaskAudit(action: string, req: Request, data: unknown) {
  const result = data as AdminTaskActionResponse

  return {
    action,
    targetType: 'task',
    targetId: String(getTaskId(req)),
    data: {
      taskId: result.task.taskId,
      taskNo: result.task.taskNo,
      status: result.task.status,
    },
  }
}

export default router
