import { Router } from 'express'

import {
  acceptAdminWorkOrders,
  addAdminMockCustomShop,
  assignAdminWorkOrderToWorker,
  cancelAdminWorkOrder,
  completeAdminWorkOrderGiftCooldown,
  confirmAdminWorkOrderFriendAdded,
  createAdminMockWorkOrder,
  deleteAdminMockCustomShop,
  deleteAdminWorkOrder,
  getAdminWorkOrderEvents,
  getAdminWorkOrderSharing,
  listAdminMockCustomShops,
  listAdminWorkOrders,
  pinAdminWorkOrder,
  publishAdminWorkOrder,
  renameAdminMockCustomShop,
  reopenAdminCancelledWorkOrder,
  reprocessAdminKuaishouSendCodeWorkOrders,
  resetAdminWorkOrderGiftMaterial,
  submitAdminWorkOrderMaterial,
  unassignAdminWorkOrder,
  unpublishAdminWorkOrder,
  updateAdminWorkOrder,
  updateAdminWorkOrderNote,
  updateAdminWorkOrderSharing,
} from '../../../services/worker-platform/index.js'
import {
  createJsonHandler,
  requireAdminPermission,
  requireAnyAdminPermission,
  requireAdminRoles,
} from '../session.js'

const router = Router()

router.get(
  '/worker-platform/orders',
  requireAdminPermission('worker_order.view'),
  createJsonHandler((req) => listAdminWorkOrders(req.query), {
    successMessage: 'ok',
    errorMessage: '读取接单订单失败',
    scope: '[admin/worker-platform/orders]',
  }),
)

router.get(
  '/worker-platform/orders/mock/custom-shops',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => ({ items: listAdminMockCustomShops() }), {
    successMessage: 'ok',
    errorMessage: '读取自定义店铺失败',
    scope: '[admin/worker-platform/orders/mock/custom-shops]',
  }),
)

router.post(
  '/worker-platform/orders/mock/custom-shops',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => addAdminMockCustomShop(String(req.body?.name || '')), {
    successMessage: '自定义店铺已新增',
    errorMessage: '新增自定义店铺失败',
    scope: '[admin/worker-platform/orders/mock/custom-shops]',
    audit: (req) => ({
      action: 'mock_custom_shop_added',
      targetType: 'mock_custom_shop',
      targetId: String(req.body?.name || ''),
      data: {},
    }),
  }),
)

router.put(
  '/worker-platform/orders/mock/custom-shops',
  requireAdminRoles(['admin']),
  createJsonHandler(
    (req) =>
      renameAdminMockCustomShop(
        String(req.body?.name || ''),
        String(req.body?.newName || req.body?.nextName || ''),
      ),
    {
      successMessage: '自定义店铺已重命名',
      errorMessage: '重命名自定义店铺失败',
      scope: '[admin/worker-platform/orders/mock/custom-shops]',
      audit: (req) => ({
        action: 'mock_custom_shop_renamed',
        targetType: 'mock_custom_shop',
        targetId: String(req.body?.name || ''),
        data: { newName: String(req.body?.newName || '') },
      }),
    },
  ),
)

router.delete(
  '/worker-platform/orders/mock/custom-shops',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => deleteAdminMockCustomShop(String(req.query?.name || '')), {
    successMessage: '自定义店铺已删除',
    errorMessage: '删除自定义店铺失败',
    scope: '[admin/worker-platform/orders/mock/custom-shops]',
    audit: (req) => ({
      action: 'mock_custom_shop_deleted',
      targetType: 'mock_custom_shop',
      targetId: String(req.query?.name || ''),
      data: {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/mock',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => createAdminMockWorkOrder(req.body || {}), {
    successMessage: '接单工单 Mock 已生成',
    errorMessage: '生成接单工单 Mock 失败',
    scope: '[admin/worker-platform/orders/mock]',
    audit: (_req, data) => ({
      action: 'work_order_mock_created',
      targetType: 'work_order',
      targetId: String((data as { order?: { workOrderId?: number } })?.order?.workOrderId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/reprocess-matches',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => reprocessAdminKuaishouSendCodeWorkOrders(req.body || {}), {
    successMessage: '快手订单重匹配完成',
    errorMessage: '快手订单重匹配失败',
    scope: '[admin/worker-platform/orders/reprocess-matches]',
    audit: (_req, data) => ({
      action: 'work_order_kuaishou_reprocessed',
      targetType: 'work_order',
      targetId: '',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/material',
  requireAdminPermission('worker_order.update_material'),
  createJsonHandler(
    (req) =>
      submitAdminWorkOrderMaterial(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '订单资料已保存',
      errorMessage: '补充订单资料失败',
      scope: '[admin/worker-platform/orders/:workOrderId/material]',
      audit: (req, data) => ({
        action: 'work_order_material_saved',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.put(
  '/worker-platform/orders/:workOrderId',
  requireAdminPermission('worker_order.edit'),
  createJsonHandler(
    (req) =>
      updateAdminWorkOrder(String(req.params.workOrderId || ''), req.body || {}, {
        canEditRequirementFields: req.adminSession?.role !== 'support',
        actorName: req.adminSession?.username || '',
      }),
    {
      successMessage: '工单信息已保存',
      errorMessage: '保存工单信息失败',
      scope: '[admin/worker-platform/orders/:workOrderId]',
      audit: (req, data) => ({
        action: 'work_order_updated',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.put(
  '/worker-platform/orders/:workOrderId/note',
  requireAdminPermission('worker_order.edit'),
  createJsonHandler(
    (req) =>
      updateAdminWorkOrderNote(
        String(req.params.workOrderId || ''),
        req.body?.note,
        req.adminSession?.username || '',
      ),
    {
      successMessage: '工单备注已保存',
      errorMessage: '保存工单备注失败',
      scope: '[admin/worker-platform/orders/:workOrderId/note]',
      audit: (req, data) => ({
        action: 'work_order_admin_note_updated',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/assign',
  requireAdminPermission('worker_order.assign'),
  createJsonHandler(
    (req) =>
      assignAdminWorkOrderToWorker(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '已指派打手',
      errorMessage: '指派打手失败',
      scope: '[admin/worker-platform/orders/:workOrderId/assign]',
      audit: (req, data) => ({
        action: 'work_order_worker_assigned',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/unassign',
  requireAdminPermission('worker_order.assign'),
  createJsonHandler(
    (req) =>
      unassignAdminWorkOrder(
        String(req.params.workOrderId || ''),
        req.adminSession?.username || '',
      ),
    {
      successMessage: '已取消指派',
      errorMessage: '取消指派失败',
      scope: '[admin/worker-platform/orders/:workOrderId/unassign]',
      audit: (req, data) => ({
        action: 'work_order_worker_unassigned',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/cancel',
  requireAnyAdminPermission(['worker_order.return_to_hall', 'worker_order.cancel']),
  createJsonHandler(
    (req) =>
      cancelAdminWorkOrder(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
        req.adminSession?.permissions || [],
      ),
    {
      successMessage: '撤单处理完成，打手额度已恢复',
      errorMessage: '撤单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/cancel]',
      audit: (req, data) => ({
        action:
          String(req.body?.action || '').trim() === 'return_to_hall'
            ? 'work_order_returned_to_hall'
            : 'work_order_cancelled',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.delete(
  '/worker-platform/orders/:workOrderId',
  requireAdminPermission('worker_order.delete'),
  createJsonHandler((req) => deleteAdminWorkOrder(String(req.params.workOrderId || '')), {
    successMessage: '工单已删除',
    errorMessage: '删除工单失败',
    scope: '[admin/worker-platform/orders/:workOrderId]',
    audit: (req, data) => ({
      action: 'work_order_deleted',
      targetType: 'work_order',
      targetId: String(req.params.workOrderId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/reopen',
  requireAdminPermission('worker_order.reopen'),
  createJsonHandler(
    (req) =>
      reopenAdminCancelledWorkOrder(
        String(req.params.workOrderId || ''),
        req.adminSession?.username || '',
      ),
    {
      successMessage: '订单已恢复为未分配状态',
      errorMessage: '重新启用订单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/reopen]',
      audit: (req, data) => ({
        action: 'work_order_reopened',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/publish',
  requireAdminPermission('worker_order.publish'),
  createJsonHandler(
    (req) =>
      publishAdminWorkOrder(String(req.params.workOrderId || ''), req.adminSession?.username || ''),
    {
      successMessage: '订单已进入大厅队列',
      errorMessage: '发布接单订单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/publish]',
      audit: (req, data) => ({
        action: 'work_order_published',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/unpublish',
  requireAdminPermission('worker_order.publish'),
  createJsonHandler(
    (req) =>
      unpublishAdminWorkOrder(
        String(req.params.workOrderId || ''),
        req.adminSession?.username || '',
      ),
    {
      successMessage: '订单已撤回到未分配',
      errorMessage: '下架接单订单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/unpublish]',
      audit: (req, data) => ({
        action: 'work_order_unpublished',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/pin',
  requireAdminPermission('worker_order.publish'),
  createJsonHandler(
    (req) =>
      pinAdminWorkOrder(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '置顶状态已更新',
      errorMessage: '更新置顶状态失败',
      scope: '[admin/worker-platform/orders/:workOrderId/pin]',
      audit: (req, data) => ({
        action: 'work_order_pin_toggled',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/confirm-friend',
  requireAdminPermission('worker_order.manage_problem'),
  createJsonHandler(
    (req) =>
      confirmAdminWorkOrderFriendAdded(
        String(req.params.workOrderId || ''),
        req.adminSession?.username || '',
      ),
    {
      successMessage: '已确认加好友，赠送冷却开始',
      errorMessage: '确认加好友失败',
      scope: '[admin/worker-platform/orders/:workOrderId/confirm-friend]',
      audit: (req, data) => ({
        action: 'work_order_friend_confirmed',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/reset-gift-material',
  requireAdminPermission('worker_order.manage_problem'),
  createJsonHandler(
    (req) =>
      resetAdminWorkOrderGiftMaterial(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '已重置打手资料，等待打手重新提交',
      errorMessage: '重置打手资料失败',
      scope: '[admin/worker-platform/orders/:workOrderId/reset-gift-material]',
      audit: (req, data) => ({
        action: 'work_order_gift_material_reset',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/complete-gift-cooldown',
  requireAdminPermission('worker_order.manage_problem'),
  createJsonHandler(
    (req) =>
      completeAdminWorkOrderGiftCooldown(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '已手动结束赠送冷却，打手现在可以提交验收',
      errorMessage: '结束赠送冷却失败',
      scope: '[admin/worker-platform/orders/:workOrderId/complete-gift-cooldown]',
      audit: (req, data) => ({
        action: 'work_order_gift_cooldown_completed',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.get(
  '/worker-platform/orders/:workOrderId/sharing',
  requireAdminPermission('worker_order.view'),
  createJsonHandler((req) => getAdminWorkOrderSharing(String(req.params.workOrderId || '')), {
    successMessage: 'ok',
    errorMessage: '读取拼单信息失败',
    scope: '[admin/worker-platform/orders/:workOrderId/sharing]',
  }),
)

router.get(
  '/worker-platform/orders/:workOrderId/events',
  requireAdminPermission('worker_order.view'),
  createJsonHandler((req) => getAdminWorkOrderEvents(String(req.params.workOrderId || '')), {
    successMessage: 'ok',
    errorMessage: '读取工单流转记录失败',
    scope: '[admin/worker-platform/orders/:workOrderId/events]',
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/sharing',
  requireAdminPermission('worker_order.configure_share'),
  createJsonHandler(
    (req) =>
      updateAdminWorkOrderSharing(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '拼单配置已保存',
      errorMessage: '保存拼单配置失败',
      scope: '[admin/worker-platform/orders/:workOrderId/sharing]',
      audit: (req, data) => ({
        action: 'work_order_sharing_config_updated',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/accept-batch',
  requireAdminPermission('worker_order.accept'),
  createJsonHandler(
    (req) => acceptAdminWorkOrders(req.body || {}, req.adminSession?.username || ''),
    {
      successMessage: '选中订单已验收通过',
      errorMessage: '批量验收接单订单失败',
      scope: '[admin/worker-platform/orders/accept-batch]',
      audit: (req, data) => ({
        action: 'work_orders_batch_accepted',
        targetType: 'work_order',
        targetId: Array.isArray(req.body?.workOrderIds)
          ? req.body.workOrderIds.map((item: unknown) => String(item)).join(',')
          : '',
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
