import { Router } from 'express'

import {
  getAdminFulfillmentRoutingConfig,
  previewAdminFulfillmentRouting,
  updateAdminFulfillmentRoutingConfig,
} from '../../../services/admin/platform-config/fulfillment-routing-service.js'
import { createJsonHandler } from '../session.js'
import type { JsonRecord } from '../../../types/json.js'

const router = Router()

router.get(
  '/fulfillment-routing',
  createJsonHandler(() => getAdminFulfillmentRoutingConfig(), {
    successMessage: 'ok',
    errorMessage: '读取履约路由配置失败',
    scope: '[admin/platform-config/fulfillment-routing]',
  }),
)

router.post(
  '/fulfillment-routing',
  createJsonHandler((req) => updateAdminFulfillmentRoutingConfig(req.body as JsonRecord), {
    successMessage: '履约路由配置已保存',
    errorMessage: '保存履约路由配置失败',
    scope: '[admin/platform-config/fulfillment-routing]',
    audit: (_req, data) => {
      const result = data as JsonRecord
      return {
        action: 'platform_fulfillment_routing_updated',
        targetType: 'platform_config',
        targetId: 'fulfillment_routing',
        data: {
          filePath: String(result.filePath || '').trim(),
          enabled: result.enabled !== false,
          ruleCount: Array.isArray(result.rules) ? result.rules.length : 0,
        },
      }
    },
  }),
)

router.post(
  '/fulfillment-routing/preview',
  createJsonHandler((req) => previewAdminFulfillmentRouting(req.body as JsonRecord), {
    successMessage: 'ok',
    errorMessage: '预览履约路由失败',
    scope: '[admin/platform-config/fulfillment-routing/preview]',
  }),
)

export default router
