import { Router } from 'express'

import {
  closeAdminTask,
  completeAdminTaskManualDispatch,
  confirmAdminTaskAssistedRole,
  dispatchAdminTaskKuaishouCloudFulfillment,
  markAdminTaskManualReview,
  prepareAdminTaskKuaishouCloudFulfillment,
  refreshAdminTaskKuaishouCloudRoleInfo,
  regenerateAdminTaskClaimLink,
  redeemAdminTaskAssisted,
  releaseAdminTaskInventoryBinding,
  releaseAdminTaskInventory,
  returnNumberAdminTaskKuaishouCloudFulfillment,
  retryAdminTask,
} from '../../services/admin/admin-write-service.js'
import {
  getAdminTaskDetail,
  getAdminTaskScreenshotPath,
  getAdminTasks,
} from '../../services/admin/admin-read-service.js'
import { createFileHandler, createJsonHandler, requireAdminRoles } from './shared.js'
import type { AdminExpressRequest } from './shared.js'
import type {
  AdminTaskKuaishouCloudDispatchRouteBody,
  AdminTaskManualDispatchRouteBody,
  AdminTaskRouteParams,
  AdminTaskRouteQuery,
} from '../../types/admin-route-inputs.js'
import type {
  AdminTaskActionResponse,
  AdminTaskBindingReleaseResponse,
  AdminTaskManualDispatchResponse,
} from '../../types/admin-write-models.js'

const router = Router()

function getTaskId(req: AdminExpressRequest): string | undefined {
  return (req.params as AdminTaskRouteParams).taskId
}

function getBindingId(req: AdminExpressRequest): string | undefined {
  return (req.params as AdminTaskRouteParams).bindingId
}

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.get('/tasks/:taskId/screenshot', createFileHandler(
  (req) => getAdminTaskScreenshotPath(
    getTaskId(req),
    req.adminSession || null,
  ),
  {
    errorMessage: '读取任务截图失败',
    scope: '[admin/tasks/:taskId/screenshot]',
  },
))

router.post('/tasks/:taskId/retry', requireAdminRoles(['admin', 'operator']), createJsonHandler(
  (req) => retryAdminTask(getTaskId(req)),
  {
    successMessage: '任务已重试',
    errorMessage: '重试任务失败',
    scope: '[admin/tasks/:taskId/retry]',
  },
))

router.post('/tasks/:taskId/release-inventory', requireAdminRoles(['admin']), createJsonHandler(
  (req) => releaseAdminTaskInventory(getTaskId(req)),
  {
    successMessage: '库存凭据已释放',
    errorMessage: '释放库存凭据失败',
    scope: '[admin/tasks/:taskId/release-inventory]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_release_inventory',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          inventoryItemId: result.task.inventoryItemId,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/inventory-bindings/:bindingId/release', requireAdminRoles(['admin']), createJsonHandler(
  (req) => releaseAdminTaskInventoryBinding(
    getTaskId(req),
    getBindingId(req),
  ),
  {
    successMessage: '库存绑定已释放',
    errorMessage: '释放库存绑定失败',
    scope: '[admin/tasks/:taskId/inventory-bindings/:bindingId/release]',
    audit: (req, data) => {
      const result = data as AdminTaskBindingReleaseResponse
      return {
        action: 'task_release_inventory_binding',
        targetType: 'task_inventory_binding',
        targetId: String(getBindingId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          bindingId: result.bindingId,
          inventoryItemId: result.inventoryItemId,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/regenerate-claim-link', requireAdminRoles(['admin', 'operator', 'support']), createJsonHandler(
  (req) => regenerateAdminTaskClaimLink(
    getTaskId(req),
    req.adminSession || null,
  ),
  {
    successMessage: '领取链接已重新生成',
    errorMessage: '重新生成领取链接失败',
    scope: '[admin/tasks/:taskId/regenerate-claim-link]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_regenerate_claim_link',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          primaryClaimTokenId: result.task.primaryClaimTokenId,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/support-confirm-role', requireAdminRoles(['admin', 'operator', 'support']), createJsonHandler(
  (req) => confirmAdminTaskAssistedRole(
    getTaskId(req),
    req.adminSession || null,
  ),
  {
    successMessage: '角色已确认',
    errorMessage: '客服确认角色失败',
    scope: '[admin/tasks/:taskId/support-confirm-role]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_support_confirm_role',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/support-redeem', requireAdminRoles(['admin', 'operator', 'support']), createJsonHandler(
  (req) => redeemAdminTaskAssisted(
    getTaskId(req),
    req.adminSession || null,
  ),
  {
    successMessage: '兑换任务已启动',
    errorMessage: '客服发起兑换失败',
    scope: '[admin/tasks/:taskId/support-redeem]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_support_redeem',
        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/close', requireAdminRoles(['admin', 'operator', 'support']), createJsonHandler(
  (req) => closeAdminTask(getTaskId(req)),
  {
    successMessage: '任务已关闭',
    errorMessage: '关闭任务失败',
    scope: '[admin/tasks/:taskId/close]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_closed',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/mark-manual-review', requireAdminRoles(['admin', 'operator']), createJsonHandler(
  (req) => markAdminTaskManualReview(getTaskId(req)),
  {
    successMessage: '任务已转人工处理',
    errorMessage: '标记人工处理失败',
    scope: '[admin/tasks/:taskId/mark-manual-review]',
    audit: (req, data) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_mark_manual_review',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

router.post('/tasks/:taskId/complete-manual-dispatch', requireAdminRoles(['admin', 'operator']), createJsonHandler(
  (req) => completeAdminTaskManualDispatch(
    getTaskId(req),
    req.body as AdminTaskManualDispatchRouteBody,
    req.adminSession || null,
  ),
  {
    successMessage: '人工履约结果已回写',
    errorMessage: '回写人工履约结果失败',
    scope: '[admin/tasks/:taskId/complete-manual-dispatch]',
    audit: (req, data) => {
      const result = data as AdminTaskManualDispatchResponse
      return {
        action: 'task_complete_manual_dispatch',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          outcome: result.outcome,
          deliveryStatus: result.task.deliveryStatus,
          resultCode: result.task.resultCode,
        },
      }
    },
  },
))

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) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_kuaishou_cloud_prepare',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

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) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_kuaishou_cloud_role_info_refreshed',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

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

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) => {
      const result = data as AdminTaskActionResponse
      return {
        action: 'task_kuaishou_cloud_return_number',
        targetType: 'task',
        targetId: String(getTaskId(req)),
        data: {
          taskId: result.task.taskId,
          taskNo: result.task.taskNo,
          status: result.task.status,
        },
      }
    },
  },
))

export default router
