import { Router } from 'express'

import {
  acceptAdminWorkOrder,
  creditAdminWorkerWallet,
  createAdminMockWorkOrder,
  deductAdminWorkOrderPendingDeposit,
  deleteAdminWorkCategory,
  deleteAdminWorkOrder,
  deleteAdminWorkerLevel,
  getAdminWorkerFinanceConfig,
  getAdminWorkerPlatformSummary,
  getAdminWorkOrderSharing,
  listAdminWorkerFinanceRequests,
  listAdminWorkCategories,
  listAdminWorkProductRules,
  listAdminWorkerLevels,
  listAdminWorkerUsers,
  listAdminWorkOrders,
  markAdminWorkOrderProblem,
  publishAdminWorkOrder,
  reviewAdminWorkerFinanceRequest,
  resolveAdminProblemWorkOrder,
  reviewAdminWorkerUser,
  saveAdminWorkerFinanceConfig,
  saveAdminWorkCategory,
  saveAdminWorkProductRule,
  saveAdminWorkerLevel,
  submitAdminWorkOrderMaterial,
  syncAdminWorkerOrdersFromSource,
  unpublishAdminWorkOrder,
  updateAdminWorkOrder,
  updateAdminWorkOrderSharing,
} from '../../services/worker-platform/index.js'
import { createJsonHandler, requireAdminRoles } from './session.js'

const router = Router()

router.get(
  '/worker-platform/summary',
  createJsonHandler(() => getAdminWorkerPlatformSummary(), {
    successMessage: 'ok',
    errorMessage: '读取接单平台概览失败',
    scope: '[admin/worker-platform/summary]',
  }),
)

router.get(
  '/worker-platform/levels',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(() => listAdminWorkerLevels(), {
    successMessage: 'ok',
    errorMessage: '读取接单等级失败',
    scope: '[admin/worker-platform/levels]',
  }),
)

router.post(
  '/worker-platform/levels',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => saveAdminWorkerLevel(req.body || {}), {
    successMessage: '接单等级已保存',
    errorMessage: '保存接单等级失败',
    scope: '[admin/worker-platform/levels]',
    audit: (_req, data) => ({
      action: 'worker_level_saved',
      targetType: 'worker_level',
      targetId: String((data as { level?: { levelKey?: string } })?.level?.levelKey || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.delete(
  '/worker-platform/levels/:levelId',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => deleteAdminWorkerLevel(String(req.params.levelId || '')), {
    successMessage: '接单等级已删除',
    errorMessage: '删除接单等级失败',
    scope: '[admin/worker-platform/levels/:levelId]',
    audit: (_req, data) => ({
      action: 'worker_level_deleted',
      targetType: 'worker_level',
      targetId: String(_req.params.levelId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/categories',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => listAdminWorkCategories(), {
    successMessage: 'ok',
    errorMessage: '读取接单分类失败',
    scope: '[admin/worker-platform/categories]',
  }),
)

router.post(
  '/worker-platform/categories',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkCategory(req.body || {}), {
    successMessage: '接单分类已保存',
    errorMessage: '保存接单分类失败',
    scope: '[admin/worker-platform/categories]',
    audit: (_req, data) => ({
      action: 'work_category_saved',
      targetType: 'work_category',
      targetId: String(
        (data as { category?: { categoryKey?: string } })?.category?.categoryKey || '',
      ),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.delete(
  '/worker-platform/categories/:categoryId',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => deleteAdminWorkCategory(String(req.params.categoryId || '')), {
    successMessage: '接单分类已删除',
    errorMessage: '删除接单分类失败',
    scope: '[admin/worker-platform/categories/:categoryId]',
    audit: (_req, data) => ({
      action: 'work_category_deleted',
      targetType: 'work_category',
      targetId: String(_req.params.categoryId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/product-rules',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminWorkProductRules(req.query), {
    successMessage: 'ok',
    errorMessage: '读取接单物品规则失败',
    scope: '[admin/worker-platform/product-rules]',
  }),
)

router.post(
  '/worker-platform/product-rules',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkProductRule(req.body || {}), {
    successMessage: '接单物品规则已保存',
    errorMessage: '保存接单物品规则失败',
    scope: '[admin/worker-platform/product-rules]',
    audit: (_req, data) => ({
      action: 'work_product_rule_saved',
      targetType: 'work_product_rule',
      targetId: String((data as { rule?: { ruleKey?: string } })?.rule?.ruleKey || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/workers',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminWorkerUsers(req.query), {
    successMessage: 'ok',
    errorMessage: '读取打手列表失败',
    scope: '[admin/worker-platform/workers]',
  }),
)

router.post(
  '/worker-platform/workers/:workerId/review',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => reviewAdminWorkerUser(String(req.params.workerId || ''), req.body || {}),
    {
      successMessage: '打手审核状态已更新',
      errorMessage: '审核打手失败',
      scope: '[admin/worker-platform/workers/:workerId/review]',
      audit: (req, data) => ({
        action: 'worker_reviewed',
        targetType: 'worker',
        targetId: String(req.params.workerId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/workers/:workerId/wallet-credit',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => creditAdminWorkerWallet(String(req.params.workerId || ''), req.body || {}),
    {
      successMessage: '打手余额已增加',
      errorMessage: '人工充值失败',
      scope: '[admin/worker-platform/workers/:workerId/wallet-credit]',
      audit: (req, data) => ({
        action: 'worker_wallet_credited',
        targetType: 'worker',
        targetId: String(req.params.workerId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.get(
  '/worker-platform/finance-config',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => getAdminWorkerFinanceConfig(), {
    successMessage: 'ok',
    errorMessage: '读取资金配置失败',
    scope: '[admin/worker-platform/finance-config]',
  }),
)

router.post(
  '/worker-platform/finance-config',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkerFinanceConfig(req.body || {}), {
    successMessage: '资金配置已保存',
    errorMessage: '保存资金配置失败',
    scope: '[admin/worker-platform/finance-config]',
    audit: (_req, data) => ({
      action: 'worker_finance_config_saved',
      targetType: 'worker_finance_config',
      targetId: 'worker_finance',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/finance-requests',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminWorkerFinanceRequests(req.query), {
    successMessage: 'ok',
    errorMessage: '读取资金申请失败',
    scope: '[admin/worker-platform/finance-requests]',
  }),
)

router.post(
  '/worker-platform/finance-requests/:requestId/review',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      reviewAdminWorkerFinanceRequest(String(req.params.requestId || ''), req.body || {}),
    {
      successMessage: '资金申请已处理',
      errorMessage: '处理资金申请失败',
      scope: '[admin/worker-platform/finance-requests/:requestId/review]',
      audit: (req, data) => ({
        action: 'worker_finance_request_reviewed',
        targetType: 'worker_finance_request',
        targetId: String(req.params.requestId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

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

router.post(
  '/worker-platform/orders/mock',
  requireAdminRoles(['admin', 'operator']),
  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/source-orders/sync',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => syncAdminWorkerOrdersFromSource(req.body || {}), {
    successMessage: '源订单同步完成',
    errorMessage: '同步源订单失败',
    scope: '[admin/worker-platform/source-orders/sync]',
    audit: (_req, data) => ({
      action: 'work_order_source_synced',
      targetType: 'source_order',
      targetId: '',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/material',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) => submitAdminWorkOrderMaterial(String(req.params.workOrderId || ''), req.body || {}),
    {
      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',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => updateAdminWorkOrder(String(req.params.workOrderId || ''), req.body || {}),
    {
      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.delete(
  '/worker-platform/orders/:workOrderId',
  requireAdminRoles(['admin', 'operator']),
  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/publish',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => publishAdminWorkOrder(String(req.params.workOrderId || '')), {
    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',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => unpublishAdminWorkOrder(String(req.params.workOrderId || '')), {
    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.get(
  '/worker-platform/orders/:workOrderId/sharing',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => getAdminWorkOrderSharing(String(req.params.workOrderId || '')), {
    successMessage: 'ok',
    errorMessage: '读取拼单信息失败',
    scope: '[admin/worker-platform/orders/:workOrderId/sharing]',
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/sharing',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => updateAdminWorkOrderSharing(String(req.params.workOrderId || ''), req.body || {}),
    {
      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/:workOrderId/problem',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) => markAdminWorkOrderProblem(String(req.params.workOrderId || ''), req.body || {}),
    {
      successMessage: '订单已标记为问题单',
      errorMessage: '标记问题单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/problem]',
      audit: (req, data) => ({
        action: 'work_order_marked_problem',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/problem/resolve',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => resolveAdminProblemWorkOrder(String(req.params.workOrderId || ''), req.body || {}),
    {
      successMessage: '问题单已处置',
      errorMessage: '处置问题单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/problem/resolve]',
      audit: (req, data) => ({
        action: 'work_order_problem_resolved',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/orders/:workOrderId/accept',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => acceptAdminWorkOrder(String(req.params.workOrderId || '')), {
    successMessage: '订单已验收通过',
    errorMessage: '验收接单订单失败',
    scope: '[admin/worker-platform/orders/:workOrderId/accept]',
    audit: (req, data) => ({
      action: 'work_order_accepted',
      targetType: 'work_order',
      targetId: String(req.params.workOrderId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/deduct-pending-deposit',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      deductAdminWorkOrderPendingDeposit(
        String(req.params.workOrderId || ''),
        req.body || {},
      ),
    {
      successMessage: '待解冻押金已扣减',
      errorMessage: '扣减待解冻押金失败',
      scope: '[admin/worker-platform/orders/:workOrderId/deduct-pending-deposit]',
      audit: (req, data) => ({
        action: 'work_order_pending_deposit_deducted',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
