import { Router } from 'express'
import {
  approveAdminKuaishouIndustryRefund,
  checkAdminKuaishouIndustryVoucherAvailable,
  consumeAdminKuaishouIndustryVoucherByCode,
  destroyAdminKuaishouIndustryVoucherByCode,
  disagreeAdminKuaishouIndustryRefund,
  listAdminKuaishouIndustryRefunds,
  listAdminKuaishouIndustryShops,
  listAdminKuaishouIndustryVouchers,
  resendAdminKuaishouIndustryVoucherCode,
  reverseAdminKuaishouIndustryVoucher,
} from '../../services/admin/kuaishou-industry-admin-service.js'
import { createJsonHandler, requireAdminRoles } from './session.js'
import type {
  AdminKuaishouIndustryRefundApproveRouteBody,
  AdminKuaishouIndustryRefundDisagreeRouteBody,
  AdminKuaishouIndustryRefundListRouteBody,
  AdminKuaishouIndustryVoucherCheckAvailableRouteBody,
  AdminKuaishouIndustryVoucherConsumeRouteBody,
  AdminKuaishouIndustryVoucherDestroyRouteBody,
  AdminKuaishouIndustryVoucherResendRouteBody,
  AdminKuaishouIndustryVoucherReverseRouteBody,
} from '../../types/admin/route-inputs.js'
import type { KuaishouIndustryVoucherAdminListQuery } from '../../repositories/kuaishou-industry-voucher-repo.js'

const router = Router()

router.get(
  '/kuaishou-industry/vouchers',
  createJsonHandler(
    (req) => listAdminKuaishouIndustryVouchers(req.query as KuaishouIndustryVoucherAdminListQuery),
    {
      successMessage: 'ok',
      errorMessage: '查询快手行业电子凭证失败',
      scope: '[admin/kuaishou-industry/vouchers]',
    },
  ),
)

router.get(
  '/kuaishou-industry/shops',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(() => listAdminKuaishouIndustryShops(), {
    successMessage: 'ok',
    errorMessage: '查询快手行业店铺失败',
    scope: '[admin/kuaishou-industry/shops]',
  }),
)

router.post(
  '/kuaishou-industry/refunds/list',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) => listAdminKuaishouIndustryRefunds(req.body as AdminKuaishouIndustryRefundListRouteBody),
    {
      successMessage: '售后单列表已查询',
      errorMessage: '查询快手售后单列表失败',
      scope: '[admin/kuaishou-industry/refunds/list]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_refund_list', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/refunds/approve',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      approveAdminKuaishouIndustryRefund(req.body as AdminKuaishouIndustryRefundApproveRouteBody),
    {
      successMessage: '同意退款接口已执行',
      errorMessage: '执行同意退款失败',
      scope: '[admin/kuaishou-industry/refunds/approve]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_refund_approve', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/refunds/disagree',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      disagreeAdminKuaishouIndustryRefund(req.body as AdminKuaishouIndustryRefundDisagreeRouteBody),
    {
      successMessage: '不同意退款接口已执行',
      errorMessage: '执行不同意退款失败',
      scope: '[admin/kuaishou-industry/refunds/disagree]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_refund_disagree', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/vouchers/check-available',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      checkAdminKuaishouIndustryVoucherAvailable(
        req.body as AdminKuaishouIndustryVoucherCheckAvailableRouteBody,
      ),
    {
      successMessage: '电子凭证有效性已检查',
      errorMessage: '检查电子凭证有效性失败',
      scope: '[admin/kuaishou-industry/vouchers/check-available]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_voucher_check_available', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/vouchers/reverse',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      reverseAdminKuaishouIndustryVoucher(req.body as AdminKuaishouIndustryVoucherReverseRouteBody),
    {
      successMessage: '电子凭证冲正回调已执行',
      errorMessage: '执行电子凭证冲正失败',
      scope: '[admin/kuaishou-industry/vouchers/reverse]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_voucher_reverse', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/vouchers/consume',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      consumeAdminKuaishouIndustryVoucherByCode(
        req.body as AdminKuaishouIndustryVoucherConsumeRouteBody,
      ),
    {
      successMessage: '电子凭证已手动核销',
      errorMessage: '手动核销电子凭证失败',
      scope: '[admin/kuaishou-industry/vouchers/consume]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_voucher_consume', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/vouchers/resend-code',
  requireAdminRoles(['admin', 'operator', 'support']),
  createJsonHandler(
    (req) =>
      resendAdminKuaishouIndustryVoucherCode(
        req.body as AdminKuaishouIndustryVoucherResendRouteBody,
      ),
    {
      successMessage: '电子凭证发码回调已重发',
      errorMessage: '重发电子凭证发码回调失败',
      scope: '[admin/kuaishou-industry/vouchers/resend-code]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_voucher_resend_code', req.body, data),
    },
  ),
)

router.post(
  '/kuaishou-industry/vouchers/destroy',
  requireAdminRoles(['admin', 'operator']),
  createJsonHandler(
    (req) =>
      destroyAdminKuaishouIndustryVoucherByCode(
        req.body as AdminKuaishouIndustryVoucherDestroyRouteBody,
      ),
    {
      successMessage: '电子凭证已手动销毁',
      errorMessage: '手动销毁电子凭证失败',
      scope: '[admin/kuaishou-industry/vouchers/destroy]',
      audit: (req, data) =>
        buildKuaishouIndustryAudit('kuaishou_industry_voucher_destroy', req.body, data),
    },
  ),
)

function buildKuaishouIndustryAudit(action: string, body: unknown, data: unknown) {
  const payload = body && typeof body === 'object' ? (body as Record<string, unknown>) : {}
  const result = data && typeof data === 'object' ? (data as Record<string, unknown>) : {}

  return {
    action,
    targetType: 'kuaishou_industry',
    targetId: resolveAuditTargetId(payload),
    data: {
      sellerId: String(payload.sellerId || ''),
      oid: String(payload.oid || payload.orderId || ''),
      voucherCode: String(payload.voucherCode || ''),
      refundId: String(payload.refundId || ''),
      success: Boolean(result.success),
      httpStatus: Number(result.httpStatus || 0) || 0,
      error: String(result.error || ''),
    },
  }
}

function resolveAuditTargetId(payload: Record<string, unknown>): string {
  return String(
    payload.voucherCode ||
      payload.refundId ||
      payload.oid ||
      payload.orderId ||
      payload.sellerId ||
      'kuaishou-industry',
  )
}

export default router
