import { Router } from 'express'

import {
  createAdminAfterSalesCase,
  getAdminAfterSalesCaseEvents,
  listAdminAfterSalesCases,
  resolveAdminAfterSalesCase,
} from '../../../services/worker-platform/index.js'
import { createJsonHandler, requireAdminRoles } from '../session.js'

const router = Router()

router.get(
  '/worker-platform/after-sales-cases',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => listAdminAfterSalesCases(req.query), {
    successMessage: 'ok',
    errorMessage: '读取售后问题单失败',
    scope: '[admin/worker-platform/after-sales-cases]',
  }),
)

router.get(
  '/worker-platform/after-sales-cases/:caseId/events',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler((req) => getAdminAfterSalesCaseEvents(String(req.params.caseId || '')), {
    successMessage: 'ok',
    errorMessage: '读取售后问题单记录失败',
    scope: '[admin/worker-platform/after-sales-cases/:caseId/events]',
  }),
)

router.post(
  '/worker-platform/orders/:workOrderId/after-sales-cases',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      createAdminAfterSalesCase(
        String(req.params.workOrderId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '售后问题单已创建',
      errorMessage: '创建售后问题单失败',
      scope: '[admin/worker-platform/orders/:workOrderId/after-sales-cases]',
      audit: (req, data) => ({
        action: 'after_sales_case_created',
        targetType: 'work_order',
        targetId: String(req.params.workOrderId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

router.post(
  '/worker-platform/after-sales-cases/:caseId/resolve',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      resolveAdminAfterSalesCase(
        String(req.params.caseId || ''),
        req.body || {},
        req.adminSession?.username || '',
      ),
    {
      successMessage: '售后问题单已处置',
      errorMessage: '处置售后问题单失败',
      scope: '[admin/worker-platform/after-sales-cases/:caseId/resolve]',
      audit: (req, data) => ({
        action: 'after_sales_case_resolved',
        targetType: 'after_sales_case',
        targetId: String(req.params.caseId || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
