import { Router } from 'express'

import {
  deleteAdminWorkCategory,
  deleteAdminWorkProductRule,
  deleteAdminWorkProductRuleMapping,
  deleteAdminWorkerLevel,
  getAdminWorkerAnnouncementConfig,
  getAdminWorkerFinanceConfig,
  getAdminWorkerHallConfig,
  getAdminWorkerPlatformNotificationConfig,
  getAdminWorkerPlatformSummary,
  getAdminWorkerProductMatchConfig,
  listAdminKuaishouMatchSources,
  listAdminWorkCategories,
  listAdminWorkProductMatchLogs,
  listAdminWorkProductRuleMappings,
  listAdminWorkProductRules,
  listAdminWorkerLevels,
  saveAdminWorkCategory,
  saveAdminWorkProductRule,
  saveAdminWorkProductRuleMapping,
  saveAdminWorkerAnnouncementConfig,
  saveAdminWorkerFinanceConfig,
  saveAdminWorkerHallConfig,
  saveAdminWorkerLevel,
  saveAdminWorkerPlatformNotificationConfig,
  saveAdminWorkerProductMatchConfig,
  syncAdminWorkProductRulePrice,
  testAdminKuaishouProductMatch,
} from '../../../services/worker-platform/index.js'
import { createJsonHandler, requireAdminRoles } from '../session.js'

const router = Router()

router.get(
  '/worker-platform/summary',
  requireAdminRoles(['admin', 'operator', 'support']),
  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.post(
  '/worker-platform/product-rules/:ruleId/sync-price',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      syncAdminWorkProductRulePrice(
        String(req.params.ruleId || ''),
        req.adminSession?.username || '',
      ),
    {
      successMessage: '模板价格已同步',
      errorMessage: '同步模板价格失败',
      scope: '[admin/worker-platform/product-rules/:ruleId/sync-price]',
      audit: (req, data) => ({
        action: 'work_product_rule_price_synced',
        targetType: 'work_product_rule',
        targetId: String(req.params.ruleId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.delete(
  '/worker-platform/product-rules/:ruleId',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => deleteAdminWorkProductRule(String(req.params.ruleId || '')), {
    successMessage: '接单物品规则已删除',
    errorMessage: '删除接单物品规则失败',
    scope: '[admin/worker-platform/product-rules/:ruleId]',
    audit: (_req, data) => ({
      action: 'work_product_rule_deleted',
      targetType: 'work_product_rule',
      targetId: String(_req.params.ruleId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/product-mappings',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminWorkProductRuleMappings(req.query), {
    successMessage: 'ok',
    errorMessage: '读取商品映射失败',
    scope: '[admin/worker-platform/product-mappings]',
  }),
)

router.post(
  '/worker-platform/product-mappings',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkProductRuleMapping(req.body || {}), {
    successMessage: '商品映射已保存',
    errorMessage: '保存商品映射失败',
    scope: '[admin/worker-platform/product-mappings]',
    audit: (_req, data) => ({
      action: 'work_product_mapping_saved',
      targetType: 'work_product_mapping',
      targetId: String((data as { mapping?: { mappingId?: number } })?.mapping?.mappingId || ''),
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.delete(
  '/worker-platform/product-mappings/:mappingId',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => deleteAdminWorkProductRuleMapping(String(req.params.mappingId || '')),
    {
      successMessage: '商品映射已删除',
      errorMessage: '删除商品映射失败',
      scope: '[admin/worker-platform/product-mappings/:mappingId]',
    },
  ),
)

router.get(
  '/worker-platform/product-match-config',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => getAdminWorkerProductMatchConfig(), {
    successMessage: 'ok',
    errorMessage: '读取商品匹配配置失败',
    scope: '[admin/worker-platform/product-match-config]',
  }),
)

router.get(
  '/worker-platform/announcement',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(() => getAdminWorkerAnnouncementConfig(), {
    successMessage: 'ok',
    errorMessage: '读取公告失败',
    scope: '[admin/worker-platform/announcement]',
  }),
)

router.get(
  '/worker-platform/hall-config',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(() => getAdminWorkerHallConfig(), {
    successMessage: 'ok',
    errorMessage: '读取大厅配置失败',
    scope: '[admin/worker-platform/hall-config]',
  }),
)

router.post(
  '/worker-platform/hall-config',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkerHallConfig(req.body || {}), {
    successMessage: '大厅配置已保存',
    errorMessage: '保存大厅配置失败',
    scope: '[admin/worker-platform/hall-config]',
    audit: (_req, data) => ({
      action: 'worker_hall_config_saved',
      targetType: 'worker_hall_config',
      targetId: 'worker_hall',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/announcement',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => saveAdminWorkerAnnouncementConfig(req.body || {}), {
    successMessage: '公告已保存',
    errorMessage: '保存公告失败',
    scope: '[admin/worker-platform/announcement]',
    audit: (_req, data) => ({
      action: 'worker_announcement_saved',
      targetType: 'worker_announcement',
      targetId: 'worker_announcement',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.post(
  '/worker-platform/product-match-config',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler((req) => saveAdminWorkerProductMatchConfig(req.body || {}), {
    successMessage: '商品匹配配置已保存',
    errorMessage: '保存商品匹配配置失败',
    scope: '[admin/worker-platform/product-match-config]',
    audit: (_req, data) => ({
      action: 'worker_product_match_config_saved',
      targetType: 'worker_product_match_config',
      targetId: 'worker_product_match',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

router.get(
  '/worker-platform/product-match-sources',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminKuaishouMatchSources(req.query), {
    successMessage: 'ok',
    errorMessage: '读取快手匹配载荷失败',
    scope: '[admin/worker-platform/product-match-sources]',
  }),
)

router.post(
  '/worker-platform/product-match-test',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => testAdminKuaishouProductMatch(req.body || {}), {
    successMessage: '匹配测试完成',
    errorMessage: '匹配测试失败',
    scope: '[admin/worker-platform/product-match-test]',
  }),
)

router.get(
  '/worker-platform/product-match-logs',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminWorkProductMatchLogs(req.query), {
    successMessage: 'ok',
    errorMessage: '读取匹配日志失败',
    scope: '[admin/worker-platform/product-match-logs]',
  }),
)

router.get(
  '/worker-platform/finance-config',
  requireAdminRoles(['admin', 'operator', 'support', 'finance']),
  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/notification-config',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(() => getAdminWorkerPlatformNotificationConfig(), {
    successMessage: 'ok',
    errorMessage: '读取通知配置失败',
    scope: '[admin/worker-platform/notification-config]',
  }),
)

router.post(
  '/worker-platform/notification-config',
  requireAdminRoles(['admin']),
  createJsonHandler((req) => saveAdminWorkerPlatformNotificationConfig(req.body || {}), {
    successMessage: '通知配置已保存',
    errorMessage: '保存通知配置失败',
    scope: '[admin/worker-platform/notification-config]',
    audit: (_req, data) => ({
      action: 'worker_platform_notification_config_saved',
      targetType: 'worker_platform_notification_config',
      targetId: 'worker_platform_notifications',
      data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
    }),
  }),
)

export default router
