import {
  completeOnboarding,
  bindAccountWechat,
  closeAccount,
  createAdminProduct,
  createAdminNewsArticle,
  createAdminNewsCategory,
  createAdminExpert,
  createAdminExpertDirection,
  createAdminCoupon,
  createAdminStaffAccount,
  createAdminOrgUnit,
  createAdminPosition,
  createAdminStaffAssignment,
  createAdminUser,
  createAdminStoredFile,
  createAdminUploadedFile,
  createStaffCheckinRegistration,
  createStaffCourseRegistration,
  createStaffEventRegistration,
  createAccountInvoiceApplication,
  createAccountStoredFile,
  createStaffStoredFile,
  createStaffUploadedFile,
  createExpertBooking,
  createExpertWithdrawal,
  createCooperationRequest,
  checkInCourseRegistrationByCode,
  checkInCourseRegistrationById,
  checkInEventRegistrationByCode,
  checkInEventRegistrationById,
  checkInStaffRegistrationByCode,
  checkInStaffRegistrationById,
  deleteAdminCourseProduct,
  deleteAdminDataProduct,
  deleteAdminEventProduct,
  deleteAdminNewsArticle,
  deleteAdminExpert,
  deleteAdminExpertDirection,
  deleteAdminCoupon,
  deleteAdminStaffAssignment,
  createDataServiceCheckout,
  createConsultingCheckout,
  createDataServiceRequest,
  createConsultingRequest,
  createExpertBookingReschedule,
  createOrder,
  createPaymentOrder,
  cancelPaymentOrder,
  cancelAdminEventRegistration,
  confirmAccountExpertBookingCompletion,
  convertAdminCooperationRequest,
  getProduct,
  getPaymentStatus,
  getPassportVerification,
  getSiteAbout,
  getSiteConsulting,
  getSiteHome,
  getDataServicePage,
  getUploadedFile,
  getAgentProduct,
  getCourseProduct,
  getDataProduct,
  getEventProduct,
  getAccountMembership,
  getAccountAiPermissions,
  getAccountOrder,
  getAccountTask,
  getAccountCourseRegistration,
  getAccountEventRegistration,
  getAccountExpertBooking,
  getMembershipCatalog,
  getNewsArticle,
  getExpert,
  getAdminExpert,
  getAdminCoupon,
  getAgreement,
  getAccountExpertApplication,
  getAccountExpertProfile,
  getAccountExpertWallet,
  getAdminOrder,
  getAdminDashboardSummary,
  getAdminPermissionCatalog,
  getAdminDataServiceRequest,
  getAdminDataServicePage,
  getAdminRevenueReport,
  getAdminStaffEffectivePermissions,
  listAdminOrgTree,
  getAdminStaffAccount,
  getAdminStaffRole,
  getAdminUserDetail,
  getAdminCooperationRequest,
  getAdminConsultingRequest,
  getAdminInvoiceApplication,
  getSiteRecommendations,
  getAccountDataServiceRequest,
  getAccountInvoiceApplication,
  getStaffDataServiceRequest,
  getStaffConsultingRequest,
  getStaffCourseRegistration,
  getStaffWorkbench,
  getStaffTask,
  listAccountConsultingRequests,
  listAccountDataServiceRequests,
  listAccountDataProducts,
  listAccountCourseRegistrations,
  listAccountEntitlements,
  listAccountEventRegistrations,
  listAccountInvoiceApplications,
  listAccountOrders,
  listAccountNotifications,
  getAccountNotificationUnreadCount,
  getAccountNotificationPreferences,
  listAccountTasks,
  listAdminCoupons,
  listAdminCouponRedemptions,
  listAdminUsers,
  listAdminCooperationRequests,
  listAdminOrders,
  listAdminPayments,
  listAdminInvoiceApplications,
  listAdminInvoiceApplicationRows,
  listAdminReconcileRows,
  listAdminStaffAccounts,
  listAdminStaffAuditLogs,
  listAdminStaffRoleAccounts,
  listAdminStaffRoles,
  listAdminProducts,
  listAdminRecommendationCandidates,
  listAdminRecommendationSlots,
  listAdminNewsArticles,
  listAdminNewsCategories,
  listAdminExperts,
  listAdminExpertDirections,
  listAdminExpertApplications,
  listAdminExpertBookings,
  listAdminExpertSlots,
  listAdminExpertWithdrawals,
  listAdminAgentProducts,
  listAdminCourseProducts,
  listAdminCourseRegistrations,
  listAdminDataProducts,
  listAdminDataCases,
  listAdminDataServiceOptions,
  listAdminDataServiceRequests,
  listAdminConsultingRequests,
  listAdminConsultingOptions,
  listAdminStaffAssignments,
  listAdminEventProducts,
  listAdminEventRegistrations,
  listAdminMembershipBenefits,
  listAdminMembershipContentDeliveries,
  listAdminMembershipEntitlements,
  listAdminMembershipPlans,
  listAdminMembershipSubscriptions,
  listAdminNotifications,
  listAdminNotificationTemplates,
  listAdminNotificationBatches,
  listAdminSettlements,
  listAgentCatalog,
  listCourseCatalog,
  listDataCatalog,
  listDataServiceOptions,
  listEventCatalog,
  listProducts,
  listNewsArticles,
  listNewsCategories,
  listFeaturedNewsArticles,
  listExperts,
  listExpertDirections,
  listExpertSlots,
  listAccountExpertBookings,
  listAccountExpertSlots,
  listExpertWithdrawals,
  listStaffConsultingRequests,
  listStaffCheckinProjects,
  listStaffCheckinRegistrations,
  listStaffDataServiceRequests,
  listStaffCourseProducts,
  listStaffCourseRegistrations,
  listStaffEventProducts,
  listStaffEventRegistrations,
  listStaffTasks,
  loginStaffByPhone,
  loginByPhone,
  miniappWechatLogin,
  bindMiniappPhone,
  createPcScanLoginSession,
  getPcScanLoginStatus,
  markPcScanLoginScanned,
  preparePcScanLogin,
  confirmPcScanLogin,
  cancelPcScanLogin,
  exchangePcScanLogin,
  startWechatOAuth,
  getWechatOAuthQrConfig,
  completeWechatOAuth,
  assignAdminMembershipManager,
  adjustAdminMembershipEntitlement,
  cancelAccountMembershipSubscription,
  cancelAdminMembershipSubscription,
  getAdminMembershipCatalog,
  manualGrantAdminMembership,
  updateAdminMembershipSubscription,
  markAccountNotificationRead,
  markAllAccountNotificationsRead,
  previewCheckout,
  previewAdminCoupon,
  publicUser,
  getStaffEventRegistration,
  getStaffMe,
  requireUser,
  requireAdmin,
  sendPhoneCode,
  setAdminProductStatus,
  setAdminStaffAccountStatus,
  setAdminCourseProductStatus,
  setAdminDataProductStatus,
  setAdminDataCaseStatus,
  setAdminEventProductStatus,
  setAdminAgentProductStatus,
  deleteAdminAgentProduct,
  setAdminNewsStatus,
  setAdminExpertStatus,
  setAccountExpertAccepting,
  disputeAccountExpertBookingCompletion,
  succeedDevPayment,
  submitExpertApplication,
  submitAccountTaskMaterials,
  searchAdminBusinessNumber,
  completeAdminCooperationRequest,
  cancelAdminConsultingRequest,
  deleteAdminNewsCategory,
  updateAdminCoupon,
  updateAdminOrgUnit,
  updateAdminOrgUnitPermissions,
  updateAdminPosition,
  updateAdminPositionPermissions,
  updateAdminRecommendationSlots,
  updateAdminDataServiceRequest,
  updateAdminDataServicePage,
  updateAdminDataServiceOptions,
  updateAdminEventRegistration,
  updateAdminConsultingRequest,
  updateAdminConsultingOptions,
  updateAdminCooperationRequest,
  updateAdminMembershipPlanBenefits,
  updateAdminStaffAccount,
  updateAdminStaffAssignment,
  updateAdminStaffDirectPermissions,
  updateAdminStaffRole,
  updateAdminUser,
  updateAdminProduct,
  updateAdminNewsArticle,
  updateAdminNewsCategory,
  updateAdminExpert,
  updateAdminExpertDirection,
  reviewAdminExpertApplication,
  respondExpertBookingReschedule,
  releaseExpiredExpertBookingHolds,
  reconcileMembershipExpiry,
  createMembershipExpiryReminders,
  createMembershipWinbackReminders,
  createAdminNotificationBatch,
  dispatchNotificationMessages,
  getAdminNotificationBatch,
  sendAdminNotificationBatch,
  retryAdminNotification,
  updateAccountNotificationPreferences,
  updateAdminNotificationTemplate,
  updateAdminAgreement,
  updateAdminExpertWithdrawal,
  updateAdminInvoiceApplication,
  updateAdminSiteAbout,
  updateAdminSiteConsulting,
  updateAdminSiteHome,
  updateStaffDataServiceRequest,
  cancelAdminDataServiceRequest,
  upsertAdminAgentProduct,
  upsertAdminCourseProduct,
  upsertAdminDataCase,
  upsertAdminDataProduct,
  upsertAdminEventProduct,
  upsertAdminMembershipBenefit,
  upsertAdminMembershipContentDelivery,
  upsertAdminMembershipPlan,
  updateProfile,
  updateAccountAiPermissions,
  updateExpertBookingStatus,
  verifyAdminPassport,
  upsertAccountExpertSlot,
  upsertExpertSlot,
  updateStaffConsultingRequest,
  updateStaffTask,
  handleWechatPayNotify,
  attachAdminInvoiceFile,
  getAdminOperationalEvent,
  handlePrometheusAlertWebhook,
  listAdminOperationalEvents,
  resolveAdminOperationalEvent,
  retryAdminOperationalEvent,
  recordOperationalEvent,
  updateAdminOperationalEvent,
} from './business-pg.mjs'
import { corsHeaders, getBearerToken, methodNotAllowed, notFound, readJsonBody, readMultipartFile, readRawBody, sendJson } from './http.mjs'
import { createStoredFileReadStream, probeObjectStorageHealth, saveRequestBodyToLocalBucket } from './file-storage.mjs'
import { captureException, incrementMetric, renderPrometheusMetrics } from './observability.mjs'
import { canUserReadUploadedFile, normalizeUploadedFileOwnerType } from './uploaded-files-repository.mjs'
import { queryJson } from './pg.mjs'
import { createWechatAiAssist } from './ai/wechat-ai-assist.mjs'

function getAdminToken(request) {
  return getBearerToken(request) || request.headers['x-admin-token'] || ''
}

function redirectToFrontend(request, response) {
  const frontendOrigin = process.env.FRONTEND_ORIGIN || process.env.WEB_ORIGIN || 'http://localhost:3000'
  response.writeHead(302, {
    location: `${frontendOrigin}${request.url || '/'}`,
    ...corsHeaders(request.headers.origin || ''),
  })
  response.end()
}

function frontendOrigin() {
  return (process.env.FRONTEND_ORIGIN || process.env.WEB_ORIGIN || 'http://localhost:3000').replace(/\/+$/, '')
}

function clientIp(request) {
  const forwarded = String(request.headers['x-forwarded-for'] || '').split(',')[0].trim()
  const realIp = String(request.headers['x-real-ip'] || '').trim()
  return forwarded || realIp || request.socket?.remoteAddress || 'unknown'
}

function authRequestMeta(request) {
  return { clientIp: clientIp(request) }
}

function metricsAuthorized(request) {
  const expected = String(process.env.METRICS_TOKEN || '').trim()
  if (!expected) return true
  return getBearerToken(request) === expected
}

const memoryRateLimitBuckets = new Map()

function enforceMemoryRateLimit(request, key, { limit = 30, windowMs = 60_000 } = {}) {
  if (process.env.RATE_LIMIT_DISABLED === 'true') return
  const now = Date.now()
  const bucketKey = `${key}:${clientIp(request)}`
  const bucket = memoryRateLimitBuckets.get(bucketKey) || { count: 0, resetAt: now + windowMs }
  if (bucket.resetAt <= now) {
    bucket.count = 0
    bucket.resetAt = now + windowMs
  }
  bucket.count += 1
  memoryRateLimitBuckets.set(bucketKey, bucket)

  if (memoryRateLimitBuckets.size > 5000) {
    for (const [currentKey, currentBucket] of memoryRateLimitBuckets.entries()) {
      if (currentBucket.resetAt <= now) memoryRateLimitBuckets.delete(currentKey)
    }
  }

  if (bucket.count > limit) {
    const error = new Error('请求过于频繁，请稍后再试')
    error.statusCode = 429
    error.code = 'rate_limited'
    error.retryAfter = Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))
    throw error
  }
}

function enforceCriticalRouteRateLimit(request, path, method) {
  if (method !== 'POST') return
  if (path === '/api/orders') {
    enforceMemoryRateLimit(request, 'orders:create', { limit: 30, windowMs: 60_000 })
    return
  }
  if (path === '/api/payment-orders') {
    enforceMemoryRateLimit(request, 'payment_orders:create', { limit: 20, windowMs: 60_000 })
    return
  }
  if (/^\/api\/(?:admin|account|staff)\/uploads(?:\/raw)?$/.test(path)) {
    enforceMemoryRateLimit(request, 'uploads:create', { limit: 30, windowMs: 60_000 })
  }
}

function redirectWithCors(request, response, location) {
  response.writeHead(302, {
    location,
    ...corsHeaders(request.headers.origin || ''),
  })
  response.end()
}

function sanitizeFrontendRedirect(value) {
  const redirect = String(value || '/').trim()
  if (!redirect || !redirect.startsWith('/') || redirect.startsWith('//')) return '/'
  return redirect.slice(0, 512)
}

function redirectWechatFailure(request, response, error, redirect = '/') {
  const target = new URL('/login', frontendOrigin())
  target.searchParams.set('redirect', sanitizeFrontendRedirect(redirect))
  target.searchParams.set('wechatError', error?.message || '微信授权失败，请重新登录')
  redirectWithCors(request, response, target.toString())
}

function fileContentDisposition(file) {
  const disposition = /^image\//i.test(file?.mimeType || '') ? 'inline' : 'attachment'
  return `${disposition}; filename*=UTF-8''${encodeURIComponent(file?.fileName || 'download')}`
}

function uploadOwnerHeaders(request) {
  return {
    ownerType: String(request.headers['x-owner-type'] || '').trim(),
    ownerId: String(request.headers['x-owner-id'] || '').trim(),
    visibility: String(request.headers['x-file-visibility'] || '').trim(),
  }
}

export async function assertCanReadUploadedFile(request, file) {
  if (!file || file.visibility === 'public') return
  const ownerType = normalizeUploadedFileOwnerType(file.ownerType)
  if (!ownerType) {
    const error = new Error('无权查看该文件')
    error.statusCode = 403
    error.code = 'file_forbidden'
    throw error
  }
  const permissionByOwner = {
    invoice_application: 'invoice:read',
    data_service_deliverable: 'data_service:read',
    data_service_request: 'data_service:read',
    withdrawal_proof: 'settlement:read',
    expert_withdrawal_proof: 'settlement:read',
    expert_material: ['expert_application:read', 'expert_booking:read'],
    expert_avatar: 'expert_profile:read',
    product_asset: 'product:read',
    cms_asset: 'site:read',
    site_asset: 'site:read',
    user_upload: 'user:read',
  }
  const adminPermissions = Array.isArray(permissionByOwner[ownerType])
    ? permissionByOwner[ownerType]
    : [permissionByOwner[ownerType]].filter(Boolean)
  for (const adminPermission of adminPermissions) {
    try {
      await requireAdmin(getAdminToken(request), adminPermission)
      return
    } catch {
      // Try the next admin permission, then fall through to account ownership check.
    }
  }
  try {
    const { user } = await requireUser(getBearerToken(request))
    if (await canUserReadUploadedFile(file, user.id)) return
  } catch {
    // Return a consistent forbidden error below.
  }
  const error = new Error('无权查看该文件')
  error.statusCode = 403
  error.code = 'file_forbidden'
  throw error
}

async function sendUploadedFile(request, response, file) {
  if ((file.storageDriver === 'local' || file.storageDriver === 's3') && file.storagePath) {
    let stream
    try {
      stream = await createStoredFileReadStream(file)
    } catch (error) {
      if (['s3_get_failed', 'ENOENT'].includes(error?.code)) {
        incrementMetric('dlbdi_file_operations_total', { status: 'failed', route: 'download' })
        await recordOperationalEvent({
          severity: 'error',
          eventType: 'file.object.missing',
          resourceType: 'uploaded_file',
          resourceId: file.id,
          message: '文件记录存在，但对象存储或本地文件无法读取',
          payload: {
            code: error.code || 'file_read_failed',
            storageDriver: file.storageDriver,
            bucket: file.bucket || '',
            objectKey: file.objectKey || '',
            storagePath: file.storagePath || '',
            ownerType: file.ownerType || '',
            ownerId: file.ownerId || '',
          },
        })
      }
      throw error
    }
    response.writeHead(200, {
      'content-type': file.mimeType || 'application/octet-stream',
      'content-length': file.fileSize || 0,
      'content-disposition': fileContentDisposition(file),
      ...corsHeaders(request.headers.origin || ''),
    })
    stream.pipe(response)
    return
  }
  const buffer = Buffer.from(file.contentBase64 || '', 'base64')
  response.writeHead(200, {
    'content-type': file.mimeType || 'application/octet-stream',
    'content-length': buffer.length,
    'content-disposition': fileContentDisposition(file),
    ...corsHeaders(request.headers.origin || ''),
  })
  response.end(buffer)
}

function csvCell(value) {
  const text = value == null ? '' : String(value)
  return `"${text.replaceAll('"', '""')}"`
}

function formatCsvDate(value) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return String(value)
  return date.toISOString()
}

function sendCsv(request, response, fileName, rows, explicitHeaders = null) {
  const defaultHeaders = [
    ['日期', 'date'],
    ['订单号', 'orderNo'],
    ['支付单号', 'paymentNo'],
    ['结算批次号', 'settlementNo'],
    ['用户手机号', 'userPhone'],
    ['商品摘要', 'itemSummary'],
    ['商品类型', 'productType'],
    ['支付渠道', 'paymentChannel'],
    ['支付状态', 'paymentStatus'],
    ['订单状态', 'orderStatus'],
    ['原价金额(分)', 'subtotalAmount'],
    ['应付金额(分)', 'totalAmount'],
    ['实付金额(分)', 'paidAmount'],
    ['会员折扣(分)', 'memberDiscountAmount'],
    ['优惠码折扣(分)', 'couponDiscountAmount'],
    ['专家应结(分)', 'expertShareAmount'],
    ['平台留存(分)', 'platformKeepAmount'],
    ['创建时间', 'createdAt'],
    ['更新时间', 'updatedAt'],
  ]
  const sample = rows[0] || {}
  const hasDefaultShape = defaultHeaders.some(([, key]) => Object.prototype.hasOwnProperty.call(sample, key))
  const headers = explicitHeaders || (hasDefaultShape || rows.length === 0
    ? defaultHeaders
    : Object.keys(sample).map((key) => [key, key]))
  const lines = [
    headers.map(([label]) => csvCell(label)).join(','),
    ...rows.map((row) => headers.map(([, key]) => {
      if (key === 'createdAt' || key === 'updatedAt') return csvCell(formatCsvDate(row[key]))
      return csvCell(row[key])
    }).join(',')),
  ]
  response.writeHead(200, {
    'content-type': 'text/csv; charset=utf-8',
    'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
    ...corsHeaders(request.headers.origin || ''),
  })
  response.end(`\ufeff${lines.join('\n')}`)
}

async function collectDeepHealth() {
  const checks = {}

  try {
    await queryJson(`select json_build_object('ok', true, 'now', now())`)
    checks.database = { status: 'ok' }
  } catch (error) {
    checks.database = { status: 'error', message: error?.message || 'database check failed' }
  }

  const smsRequired = process.env.NODE_ENV === 'production' && process.env.ENABLE_DEV_AUTH_CODE !== 'true'
  const smsConfigured = Boolean(
    process.env.ALIBABA_CLOUD_ACCESS_KEY_ID
    && process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
    && process.env.ALIBABA_CLOUD_SMS_SIGN_NAME
    && process.env.ALIBABA_CLOUD_SMS_TEMPLATE_CODE,
  )
  checks.sms = {
    status: !smsRequired || smsConfigured ? 'ok' : 'error',
    configured: smsConfigured,
  }

  const wechatPayEnabled = process.env.WECHAT_PAY_ENABLED === 'true'
  const wechatPayConfigured = Boolean(
    process.env.WECHAT_PAY_MCH_ID
    && process.env.WECHAT_PAY_APP_ID
    && process.env.WECHAT_PAY_API_V3_KEY
    && process.env.WECHAT_PAY_MCH_SERIAL_NO
    && (process.env.WECHAT_PAY_PRIVATE_KEY_PATH || process.env.WECHAT_PAY_PRIVATE_KEY_BASE64)
    && process.env.WECHAT_PAY_PUBLIC_KEY_ID
    && (process.env.WECHAT_PAY_PUBLIC_KEY_PATH || process.env.WECHAT_PAY_PUBLIC_KEY_BASE64)
    && process.env.WECHAT_PAY_NOTIFY_URL,
  )
  checks.wechatPay = {
    status: !wechatPayEnabled || wechatPayConfigured ? 'ok' : 'error',
    enabled: wechatPayEnabled,
    configured: wechatPayConfigured,
  }

  checks.objectStorage = await probeObjectStorageHealth()
  if (checks.objectStorage.status === 'error') {
    await recordOperationalEvent({
      severity: 'error',
      eventType: 'file.storage.probe_failed',
      resourceType: 'object_storage',
      resourceId: checks.objectStorage.bucket || 'default',
      message: checks.objectStorage.message || '对象存储健康探测失败',
      payload: {
        code: checks.objectStorage.code || 'object_storage_probe_failed',
        driver: checks.objectStorage.driver,
        bucket: checks.objectStorage.bucket || '',
        configured: checks.objectStorage.configured,
      },
    }).catch(() => {})
  }

  const failed = Object.values(checks).some((check) => check.status === 'error')
  const warning = Object.values(checks).some((check) => check.status === 'warning')

  return {
    status: failed ? 'error' : warning ? 'degraded' : 'ok',
    service: 'dlbdi-backend',
    mode: 'lite-postgres',
    timestamp: new Date().toISOString(),
    checks,
  }
}

function configCheck({ key, group, label, status, required = false, configured = false, message = '', suggestion = '', details = {} }) {
  return {
    key,
    group,
    label,
    status,
    required,
    configured,
    message,
    suggestion,
    details,
  }
}

async function collectSystemConfigChecks() {
  const isProduction = process.env.NODE_ENV === 'production'
  const explicitOrigins = String(process.env.CORS_ALLOW_ORIGINS || process.env.FRONTEND_ORIGIN || process.env.WEB_ORIGIN || '').trim()
  const corsLooksOpen = !isProduction && !explicitOrigins
  const apiInternalUrl = String(process.env.API_INTERNAL_URL || process.env.SERVER_API_BASE_URL || '').trim()
  const publicApiBaseUrl = String(process.env.NEXT_PUBLIC_API_BASE_URL || '').trim()
  const smsConfigured = Boolean(
    process.env.ALIBABA_CLOUD_ACCESS_KEY_ID
    && process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
    && process.env.ALIBABA_CLOUD_SMS_SIGN_NAME
    && process.env.ALIBABA_CLOUD_SMS_TEMPLATE_CODE,
  )
  const wechatPayEnabled = process.env.WECHAT_PAY_ENABLED === 'true'
  const wechatPayConfigured = Boolean(
    process.env.WECHAT_PAY_MCH_ID
    && process.env.WECHAT_PAY_APP_ID
    && process.env.WECHAT_PAY_API_V3_KEY
    && process.env.WECHAT_PAY_MCH_SERIAL_NO
    && (process.env.WECHAT_PAY_PRIVATE_KEY_PATH || process.env.WECHAT_PAY_PRIVATE_KEY_BASE64)
    && process.env.WECHAT_PAY_PUBLIC_KEY_ID
    && (process.env.WECHAT_PAY_PUBLIC_KEY_PATH || process.env.WECHAT_PAY_PUBLIC_KEY_BASE64)
    && process.env.WECHAT_PAY_NOTIFY_URL,
  )
  const objectStorage = await probeObjectStorageHealth()
  const items = [
    configCheck({
      key: 'cors',
      group: '安全',
      label: 'CORS 域名限制',
      status: isProduction && !explicitOrigins ? 'error' : corsLooksOpen ? 'warning' : 'ok',
      required: isProduction,
      configured: Boolean(explicitOrigins),
      message: explicitOrigins ? `已配置 ${explicitOrigins}` : (isProduction ? '生产环境未限制前端域名' : '本地环境允许开放 CORS'),
      suggestion: '生产环境配置 CORS_ALLOW_ORIGINS 为 Web 域名，避免任意站点调用后台 API。',
      details: { nodeEnv: process.env.NODE_ENV || '', allowOrigins: explicitOrigins || '*' },
    }),
    configCheck({
      key: 'rate_limit',
      group: '登录',
      label: '登录、下单、支付与上传限流',
      status: process.env.RATE_LIMIT_DISABLED === 'true' && isProduction ? 'error' : 'ok',
      required: true,
      configured: process.env.RATE_LIMIT_DISABLED !== 'true',
      message: process.env.RATE_LIMIT_DISABLED === 'true' ? '限流被显式关闭' : '限流逻辑处于启用状态',
      suggestion: '生产环境不要关闭登录、验证码、下单、支付单创建和上传等关键接口限流。',
    }),
    configCheck({
      key: 'api_internal_url',
      group: '网络',
      label: 'SSR 内部 API 地址',
      status: apiInternalUrl ? 'ok' : 'warning',
      required: isProduction,
      configured: Boolean(apiInternalUrl),
      message: apiInternalUrl || '未配置 API_INTERNAL_URL 或 SERVER_API_BASE_URL',
      suggestion: '容器部署时配置 API_INTERNAL_URL=http://backend:4000/api 或 SERVER_API_BASE_URL=http://backend:4000/api，避免 SSR 使用相对地址。',
    }),
    configCheck({
      key: 'public_api_base_url',
      group: '网络',
      label: '浏览器 API 地址',
      status: publicApiBaseUrl ? 'ok' : 'warning',
      required: true,
      configured: Boolean(publicApiBaseUrl),
      message: publicApiBaseUrl || '未配置 NEXT_PUBLIC_API_BASE_URL',
      suggestion: '浏览器端建议使用 /api 走网关代理；SSR 另用 API_INTERNAL_URL。',
    }),
    configCheck({
      key: 'object_storage',
      group: '文件',
      label: '对象存储',
      status: objectStorage.status === 'error' ? 'error' : objectStorage.status === 'warning' ? 'warning' : 'ok',
      required: Boolean(objectStorage.required),
      configured: Boolean(objectStorage.configured),
      message: objectStorage.message || (objectStorage.driver === 'local' ? '本地上传模式可用' : '对象存储可用'),
      suggestion: objectStorage.driver === 'local' ? '本地开发可用；生产上线前配置 S3 兼容对象存储。' : '确认 bucket、region、endpoint、签名版本和密钥一致。',
      details: objectStorage,
    }),
    configCheck({
      key: 'wechat_pay',
      group: '支付',
      label: '微信支付配置',
      status: !wechatPayEnabled ? 'warning' : wechatPayConfigured ? 'ok' : 'error',
      required: wechatPayEnabled || isProduction,
      configured: wechatPayConfigured,
      message: !wechatPayEnabled ? '微信支付未启用' : wechatPayConfigured ? '微信支付配置完整' : '微信支付启用但配置不完整',
      suggestion: '检查商户号、AppID、APIv3 Key、证书、公钥、回调地址。',
    }),
    configCheck({
      key: 'wechat_pay_notify',
      group: '支付',
      label: '支付回调地址',
      status: !wechatPayEnabled ? 'warning' : process.env.WECHAT_PAY_NOTIFY_URL ? 'ok' : 'error',
      required: wechatPayEnabled,
      configured: Boolean(process.env.WECHAT_PAY_NOTIFY_URL),
      message: process.env.WECHAT_PAY_NOTIFY_URL || '未配置 WECHAT_PAY_NOTIFY_URL',
      suggestion: '生产回调地址必须是公网 HTTPS，并能到达 /api/payments/wechat/notify。',
    }),
    configCheck({
      key: 'sms',
      group: '登录',
      label: '短信验证码',
      status: isProduction && !smsConfigured ? 'error' : smsConfigured ? 'ok' : 'warning',
      required: isProduction,
      configured: smsConfigured,
      message: smsConfigured ? '短信配置完整' : '短信配置不完整，本地可使用开发验证码',
      suggestion: '生产环境配置阿里云短信 key、签名和模板。',
    }),
    configCheck({
      key: 'upload_limit',
      group: '文件',
      label: '上传大小限制',
      status: process.env.RAW_UPLOAD_MAX_BYTES || process.env.UPLOAD_MAX_BYTES ? 'ok' : 'warning',
      required: isProduction,
      configured: Boolean(process.env.RAW_UPLOAD_MAX_BYTES || process.env.UPLOAD_MAX_BYTES),
      message: process.env.RAW_UPLOAD_MAX_BYTES
        ? `raw 上传限制 ${process.env.RAW_UPLOAD_MAX_BYTES} bytes`
        : process.env.UPLOAD_MAX_BYTES
          ? `普通请求限制 ${process.env.UPLOAD_MAX_BYTES} bytes`
          : '未显式配置 RAW_UPLOAD_MAX_BYTES，默认 raw 上传限制 1GB',
      suggestion: '生产建议 RAW_UPLOAD_MAX_BYTES=1073741824，并同步检查 Nginx/Caddy client_max_body_size，避免后台上传大文件出现 413。',
    }),
  ]
  const summary = items.reduce((acc, item) => {
    acc.total += 1
    acc[item.status] = (acc[item.status] || 0) + 1
    return acc
  }, { total: 0, ok: 0, warning: 0, error: 0 })
  return { items, summary, generatedAt: new Date().toISOString() }
}

const opsJobDefinitions = [
  {
    key: 'membership-expiry-reconcile',
    name: '会员过期同步',
    description: '校准过期订阅和用户会员缓存。',
    permission: 'operations:write',
  },
  {
    key: 'object-storage-probe',
    name: '对象存储探测',
    description: '立即探测当前对象存储或本地上传模式。',
    permission: 'operations:write',
  },
]

function listSystemOpsJobs() {
  return {
    items: opsJobDefinitions.map((job) => ({
      ...job,
      status: 'ready',
      lastRunAt: null,
      lastResult: null,
    })),
  }
}

async function runSystemOpsJob(token, jobKey) {
  const job = opsJobDefinitions.find((item) => item.key === jobKey)
  if (!job) {
    const error = new Error('运维任务不存在')
    error.statusCode = 404
    error.code = 'ops_job_not_found'
    throw error
  }
  await requireAdmin(token, job.permission)
  const startedAt = new Date().toISOString()
  if (job.key === 'membership-expiry-reconcile') {
    return { ...job, startedAt, finishedAt: new Date().toISOString(), result: await reconcileMembershipExpiry(token) }
  }
  if (job.key === 'object-storage-probe') {
    return { ...job, startedAt, finishedAt: new Date().toISOString(), result: await probeObjectStorageHealth() }
  }
  return { ...job, startedAt, finishedAt: new Date().toISOString(), result: { ok: true } }
}

export async function handleLiteApi(request, response) {
  const url = new URL(request.url || '/', 'http://localhost')
  const method = request.method || 'GET'
  const path = url.pathname

  if (method === 'GET' && path === '/api/health') {
    sendJson(response, 200, {
      status: 'ok',
      service: 'dlbdi-backend',
      mode: 'lite-postgres',
      storage: 'postgres',
      version: '0.1.0',
      timestamp: new Date().toISOString(),
    })
    return
  }

  if (method === 'GET' && path === '/api/metrics') {
    if (!metricsAuthorized(request)) {
      sendJson(response, 401, {
        error: 'metrics_unauthorized',
        message: 'Metrics token is invalid',
      })
      return
    }
    response.writeHead(200, {
      'content-type': 'text/plain; version=0.0.4; charset=utf-8',
      ...corsHeaders(request.headers.origin || ''),
    })
    response.end(renderPrometheusMetrics())
    return
  }

  if (method === 'GET' && path === '/api/health/deep') {
    const health = await collectDeepHealth()
    sendJson(response, health.status === 'error' ? 503 : 200, health)
    return
  }

  if ((method === 'GET' || method === 'HEAD') && /^\/(admin|staff)(?:\/|$)/.test(path)) {
    redirectToFrontend(request, response)
    return
  }

  try {
    enforceCriticalRouteRateLimit(request, path, method)

    if (method === 'POST' && path === '/api/internal/alerts/prometheus') {
      sendJson(response, 202, await handlePrometheusAlertWebhook(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/admin/system/health') {
      if (method !== 'GET') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'operations:read')
      sendJson(response, 200, await collectDeepHealth())
      return
    }

    if (path === '/api/admin/system/config-checks') {
      if (method !== 'GET') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'operations:read')
      sendJson(response, 200, await collectSystemConfigChecks())
      return
    }

    if (path === '/api/admin/system/jobs') {
      if (method !== 'GET') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'operations:read')
      sendJson(response, 200, listSystemOpsJobs())
      return
    }

    const adminSystemJobRunMatch = path.match(/^\/api\/admin\/system\/jobs\/([^/]+)\/run$/)
    if (adminSystemJobRunMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await runSystemOpsJob(getAdminToken(request), decodeURIComponent(adminSystemJobRunMatch[1])))
      return
    }

    if (path === '/api/auth/phone/send-code') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await sendPhoneCode((await readJsonBody(request)).phone, authRequestMeta(request)))
      return
    }

    if (path === '/api/admin/uploads') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createAdminUploadedFile(getAdminToken(request), {
        ...await readMultipartFile(request),
        ...uploadOwnerHeaders(request),
      }))
      return
    }

    if (path === '/api/admin/uploads/raw') {
      if (method !== 'POST') return methodNotAllowed(response)
      const storedFile = await saveRequestBodyToLocalBucket(
        request,
        decodeURIComponent(request.headers['x-file-name'] || 'download'),
      )
      sendJson(response, 201, await createAdminStoredFile(getAdminToken(request), {
        ...storedFile,
        mimeType: request.headers['content-type'] || 'application/octet-stream',
        ...uploadOwnerHeaders(request),
      }))
      return
    }

    if (path === '/api/account/uploads/raw') {
      if (method !== 'POST') return methodNotAllowed(response)
      const storedFile = await saveRequestBodyToLocalBucket(
        request,
        decodeURIComponent(request.headers['x-file-name'] || 'download'),
      )
      sendJson(response, 201, await createAccountStoredFile(getBearerToken(request), {
        ...storedFile,
        mimeType: request.headers['content-type'] || 'application/octet-stream',
        ...uploadOwnerHeaders(request),
      }))
      return
    }

    if (path === '/api/staff/uploads') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createStaffUploadedFile(getAdminToken(request), {
        ...await readMultipartFile(request),
        ...uploadOwnerHeaders(request),
      }))
      return
    }

    if (path === '/api/staff/uploads/raw') {
      if (method !== 'POST') return methodNotAllowed(response)
      const storedFile = await saveRequestBodyToLocalBucket(
        request,
        decodeURIComponent(request.headers['x-file-name'] || 'download'),
      )
      sendJson(response, 201, await createStaffStoredFile(getAdminToken(request), {
        ...storedFile,
        mimeType: request.headers['content-type'] || 'application/octet-stream',
        ...uploadOwnerHeaders(request),
      }))
      return
    }

    if (path.startsWith('/api/files/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const file = await getUploadedFile(decodeURIComponent(path.replace('/api/files/', '')))
      if (!file) return notFound(response)
      await assertCanReadUploadedFile(request, file)
      await sendUploadedFile(request, response, file)
      return
    }

    if (path === '/api/auth/phone/login') {
      if (method !== 'POST') return methodNotAllowed(response)
      const body = await readJsonBody(request)
      sendJson(response, 200, await loginByPhone(body.phone, body.code, authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/miniapp/wechat-login') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await miniappWechatLogin(await readJsonBody(request), authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/miniapp/bind-phone') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await bindMiniappPhone(await readJsonBody(request), authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/pc-scan/create') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createPcScanLoginSession(await readJsonBody(request), authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/pc-scan/status') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getPcScanLoginStatus(url.searchParams.get('sessionId') || ''))
      return
    }

    if (path === '/api/auth/pc-scan/scanned') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await markPcScanLoginScanned(await readJsonBody(request), authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/pc-scan/prepare') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await preparePcScanLogin(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/auth/pc-scan/confirm') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await confirmPcScanLogin(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/auth/pc-scan/cancel') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelPcScanLogin(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/auth/pc-scan/exchange') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await exchangePcScanLogin(await readJsonBody(request), authRequestMeta(request)))
      return
    }

    if (path === '/api/auth/wechat/start') {
      sendJson(response, 410, {
        error: 'wechat_web_oauth_disabled',
        message: '电脑端微信登录已改为小程序码扫码登录',
      })
      return
    }

    if (path === '/api/auth/wechat/qr-config') {
      sendJson(response, 410, {
        error: 'wechat_web_oauth_disabled',
        message: '电脑端微信登录已改为小程序码扫码登录',
      })
      return
    }

    if (path === '/api/auth/wechat/callback') {
      redirectWechatFailure(request, response, new Error('电脑端微信登录已改为小程序码扫码登录'))
      return
    }

    if (path === '/api/auth/wechat/login') {
      sendJson(response, 410, {
        error: 'wechat_legacy_login_disabled',
        message: '微信登录已切换为微信授权，请使用 /api/auth/wechat/start',
      })
      return
    }

    if (path === '/api/staff-auth/phone-login') {
      if (method !== 'POST') return methodNotAllowed(response)
      const body = await readJsonBody(request)
      sendJson(response, 200, await loginStaffByPhone(body.phone, body.code, authRequestMeta(request)))
      return
    }

    if (path === '/api/staff-auth/me') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getStaffMe(getAdminToken(request)))
      return
    }

    if (path === '/api/staff/workbench') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getStaffWorkbench(getAdminToken(request)))
      return
    }

    if (path === '/api/staff/checkin/projects') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffCheckinProjects(getAdminToken(request), {
          kind: url.searchParams.get('kind') || 'all',
          range: url.searchParams.get('range') || 'all',
        }),
      })
      return
    }

    if (path === '/api/staff/checkin/registrations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listStaffCheckinRegistrations(getAdminToken(request), {
        kind: url.searchParams.get('kind') || 'event',
        productId: url.searchParams.get('productId') || url.searchParams.get('eventId') || url.searchParams.get('courseId') || '',
        status: url.searchParams.get('status') || '',
        keyword: url.searchParams.get('keyword') || '',
        page: url.searchParams.get('page') || '1',
        pageSize: url.searchParams.get('pageSize') || '50',
      }))
      return
    }

    if (path === '/api/staff/checkin/scan') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await checkInStaffRegistrationByCode(getAdminToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/staff/checkin/manual') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await checkInStaffRegistrationById(getAdminToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/staff/checkin/passport-registration') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await createStaffCheckinRegistration(getAdminToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/admin/staff-accounts') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminStaffAccounts(getAdminToken(request), {
            search: url.searchParams.get('search') || '',
            status: url.searchParams.get('status') || '',
            role: url.searchParams.get('role') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminStaffAccount(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminStaffAccountStatusMatch = path.match(/^\/api\/admin\/staff-accounts\/([^/]+)\/(disable|enable)$/)
    if (adminStaffAccountStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminStaffAccountStatus(
          getAdminToken(request),
          decodeURIComponent(adminStaffAccountStatusMatch[1]),
          adminStaffAccountStatusMatch[2] === 'disable' ? 'disabled' : 'active',
        ),
      )
      return
    }

    const adminStaffEffectivePermissionsMatch = path.match(/^\/api\/admin\/staff-accounts\/([^/]+)\/effective-permissions$/)
    if (adminStaffEffectivePermissionsMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminStaffEffectivePermissions(
        getAdminToken(request),
        decodeURIComponent(adminStaffEffectivePermissionsMatch[1]),
      ))
      return
    }

    const adminStaffDirectPermissionsMatch = path.match(/^\/api\/admin\/staff-accounts\/([^/]+)\/direct-permissions$/)
    if (adminStaffDirectPermissionsMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminStaffDirectPermissions(
        getAdminToken(request),
        decodeURIComponent(adminStaffDirectPermissionsMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminStaffAssignmentMatch = path.match(/^\/api\/admin\/staff-accounts\/([^/]+)\/assignments\/([^/]+)$/)
    if (adminStaffAssignmentMatch) {
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminStaffAssignment(
          getAdminToken(request),
          decodeURIComponent(adminStaffAssignmentMatch[1]),
          decodeURIComponent(adminStaffAssignmentMatch[2]),
          await readJsonBody(request),
        ))
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminStaffAssignment(
          getAdminToken(request),
          decodeURIComponent(adminStaffAssignmentMatch[1]),
          decodeURIComponent(adminStaffAssignmentMatch[2]),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    const adminStaffAccountMatch = path.match(/^\/api\/admin\/staff-accounts\/([^/]+)$/)
    if (adminStaffAccountMatch) {
      if (method === 'GET') {
        const account = await getAdminStaffAccount(getAdminToken(request), decodeURIComponent(adminStaffAccountMatch[1]))
        if (!account) return notFound(response)
        sendJson(response, 200, account)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminStaffAccount(
          getAdminToken(request),
          decodeURIComponent(adminStaffAccountMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/staff-roles') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listAdminStaffRoles(getAdminToken(request)) })
      return
    }

    const adminStaffRoleAccountsMatch = path.match(/^\/api\/admin\/staff-roles\/([^/]+)\/accounts$/)
    if (adminStaffRoleAccountsMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminStaffRoleAccounts(
        getAdminToken(request),
        decodeURIComponent(adminStaffRoleAccountsMatch[1]),
      ))
      return
    }

    const adminStaffRoleMatch = path.match(/^\/api\/admin\/staff-roles\/([^/]+)$/)
    if (adminStaffRoleMatch) {
      if (method === 'GET') {
        const role = await getAdminStaffRole(getAdminToken(request), decodeURIComponent(adminStaffRoleMatch[1]))
        if (!role) return notFound(response)
        sendJson(response, 200, role)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminStaffRole(
          getAdminToken(request),
          decodeURIComponent(adminStaffRoleMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/permission-catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminPermissionCatalog(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/org-tree') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminOrgTree(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/org-units') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createAdminOrgUnit(getAdminToken(request), await readJsonBody(request)))
      return
    }

    const adminOrgUnitPermissionsMatch = path.match(/^\/api\/admin\/org-units\/([^/]+)\/permissions$/)
    if (adminOrgUnitPermissionsMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminOrgUnitPermissions(
        getAdminToken(request),
        decodeURIComponent(adminOrgUnitPermissionsMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminOrgUnitStatusMatch = path.match(/^\/api\/admin\/org-units\/([^/]+)\/status$/)
    if (adminOrgUnitStatusMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminOrgUnit(
        getAdminToken(request),
        decodeURIComponent(adminOrgUnitStatusMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminOrgUnitSortMatch = path.match(/^\/api\/admin\/org-units\/([^/]+)\/sort$/)
    if (adminOrgUnitSortMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminOrgUnit(
        getAdminToken(request),
        decodeURIComponent(adminOrgUnitSortMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminOrgUnitMatch = path.match(/^\/api\/admin\/org-units\/([^/]+)$/)
    if (adminOrgUnitMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminOrgUnit(
        getAdminToken(request),
        decodeURIComponent(adminOrgUnitMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/positions') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createAdminPosition(getAdminToken(request), await readJsonBody(request)))
      return
    }

    const adminPositionPermissionsMatch = path.match(/^\/api\/admin\/positions\/([^/]+)\/permissions$/)
    if (adminPositionPermissionsMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminPositionPermissions(
        getAdminToken(request),
        decodeURIComponent(adminPositionPermissionsMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminPositionStatusMatch = path.match(/^\/api\/admin\/positions\/([^/]+)\/status$/)
    if (adminPositionStatusMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminPosition(
        getAdminToken(request),
        decodeURIComponent(adminPositionStatusMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminPositionSortMatch = path.match(/^\/api\/admin\/positions\/([^/]+)\/sort$/)
    if (adminPositionSortMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminPosition(
        getAdminToken(request),
        decodeURIComponent(adminPositionSortMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminPositionMatch = path.match(/^\/api\/admin\/positions\/([^/]+)$/)
    if (adminPositionMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminPosition(
        getAdminToken(request),
        decodeURIComponent(adminPositionMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/staff-assignments') {
      if (method === 'GET') {
        sendJson(response, 200, await listAdminStaffAssignments(getAdminToken(request)))
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminStaffAssignment(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/staff-audit-logs') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminStaffAuditLogs(getAdminToken(request), {
          search: url.searchParams.get('search') || '',
          action: url.searchParams.get('action') || '',
          source: url.searchParams.get('source') || '',
          targetType: url.searchParams.get('targetType') || url.searchParams.get('target_type') || '',
          dateFrom: url.searchParams.get('dateFrom') || url.searchParams.get('date_from') || '',
          dateTo: url.searchParams.get('dateTo') || url.searchParams.get('date_to') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/passports/verify') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await verifyAdminPassport(getAdminToken(request), url.searchParams.get('q') || ''))
      return
    }

    if (path === '/api/account/me') {
      if (method !== 'GET') return methodNotAllowed(response)
      const { user } = await requireUser(getBearerToken(request))
      sendJson(response, 200, publicUser(user))
      return
    }

    if (path === '/api/account/membership') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAccountMembership(getBearerToken(request)))
      return
    }

    if (path === '/api/account/ai-permissions') {
      if (method === 'GET') {
        sendJson(response, 200, await getAccountAiPermissions(getBearerToken(request)))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAccountAiPermissions(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const accountMembershipCancelMatch = path.match(/^\/api\/account\/membership\/subscriptions\/([^/]+)\/cancel$/)
    if (accountMembershipCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelAccountMembershipSubscription(
        getBearerToken(request),
        decodeURIComponent(accountMembershipCancelMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/account/notifications') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAccountNotifications(getBearerToken(request), {
        unreadOnly: url.searchParams.get('unreadOnly') || '',
        readState: url.searchParams.get('readState') || url.searchParams.get('read_state') || '',
        category: url.searchParams.get('category') || '',
        scene: url.searchParams.get('scene') || '',
        page: url.searchParams.get('page') || '',
        pageSize: url.searchParams.get('pageSize') || url.searchParams.get('page_size') || '',
      }))
      return
    }

    if (path === '/api/account/notifications/unread-count') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAccountNotificationUnreadCount(getBearerToken(request)))
      return
    }

    if (path === '/api/account/notifications/read-all') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await markAllAccountNotificationsRead(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/notification-preferences') {
      if (method === 'GET') {
        sendJson(response, 200, await getAccountNotificationPreferences(getBearerToken(request)))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAccountNotificationPreferences(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const accountNotificationReadMatch = path.match(/^\/api\/account\/notifications\/([^/]+)\/read$/)
    if (accountNotificationReadMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await markAccountNotificationRead(getBearerToken(request), decodeURIComponent(accountNotificationReadMatch[1])))
      return
    }

    if (path === '/api/account/profile') {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateProfile(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/wechat') {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await bindAccountWechat(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/close') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await closeAccount(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/onboarding') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await completeOnboarding(getBearerToken(request), await readJsonBody(request)))
      return
    }

    const passportMatch = path.match(/^\/api\/passports\/([^/]+)$/)
    if (passportMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const verification = await getPassportVerification(decodeURIComponent(passportMatch[1]))
      if (!verification) return notFound(response)
      sendJson(response, 200, verification)
      return
    }

    if (path === '/api/admin/users') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminUsers(getAdminToken(request), {
            search: url.searchParams.get('search') || '',
            status: url.searchParams.get('status') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminUser(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminUserMatch = path.match(/^\/api\/admin\/users\/([^/]+)$/)
    if (adminUserMatch) {
      if (method === 'GET') {
        const detail = await getAdminUserDetail(getAdminToken(request), decodeURIComponent(adminUserMatch[1]))
        if (!detail) return notFound(response)
        sendJson(response, 200, detail)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminUser(
        getAdminToken(request),
        decodeURIComponent(adminUserMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/memberships') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminMembershipSubscriptions(getAdminToken(request), {
          search: url.searchParams.get('search') || '',
          tier: url.searchParams.get('tier') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/memberships/manual-grant') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await manualGrantAdminMembership(getAdminToken(request), await readJsonBody(request)))
      return
    }

    const adminMembershipMatch = path.match(/^\/api\/admin\/memberships\/([^/]+)$/)
    if (adminMembershipMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminMembershipSubscription(
        getAdminToken(request),
        decodeURIComponent(adminMembershipMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminMembershipActionMatch = path.match(/^\/api\/admin\/memberships\/([^/]+)\/(cancel|assign-manager)$/)
    if (adminMembershipActionMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      const id = decodeURIComponent(adminMembershipActionMatch[1])
      const action = adminMembershipActionMatch[2]
      if (action === 'assign-manager') {
        sendJson(response, 200, await assignAdminMembershipManager(getAdminToken(request), id, await readJsonBody(request)))
        return
      }
      sendJson(response, 200, await cancelAdminMembershipSubscription(getAdminToken(request), id, {
        ...(await readJsonBody(request)),
      }))
      return
    }

    if (path === '/api/admin/memberships/jobs/expire') {
      if (method !== 'POST') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'operations:write')
      sendJson(response, 200, await reconcileMembershipExpiry(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/memberships/jobs/expiry-reminders') {
      if (method !== 'POST') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'ops_job:run')
      sendJson(response, 200, await createMembershipExpiryReminders(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/memberships/jobs/winback-reminders') {
      if (method !== 'POST') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'ops_job:run')
      sendJson(response, 200, await createMembershipWinbackReminders(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/notifications') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminNotifications(getAdminToken(request), {
        scene: url.searchParams.get('scene') || '',
        status: url.searchParams.get('status') || '',
        category: url.searchParams.get('category') || '',
        channel: url.searchParams.get('channel') || '',
        batchId: url.searchParams.get('batchId') || url.searchParams.get('batch_id') || '',
        page: url.searchParams.get('page') || '',
        pageSize: url.searchParams.get('pageSize') || url.searchParams.get('page_size') || '',
      }))
      return
    }

    const adminNotificationRetryMatch = path.match(/^\/api\/admin\/notifications\/([^/]+)\/retry$/)
    if (adminNotificationRetryMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await retryAdminNotification(getAdminToken(request), decodeURIComponent(adminNotificationRetryMatch[1])))
      return
    }

    if (path === '/api/admin/notifications/dispatch') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await dispatchNotificationMessages(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/notification-templates') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminNotificationTemplates(getAdminToken(request), {
          search: url.searchParams.get('search') || '',
          scene: url.searchParams.get('scene') || '',
          category: url.searchParams.get('category') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminNotificationTemplateMatch = path.match(/^\/api\/admin\/notification-templates\/([^/]+)$/)
    if (adminNotificationTemplateMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminNotificationTemplate(
        getAdminToken(request),
        decodeURIComponent(adminNotificationTemplateMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/notification-batches') {
      if (method === 'GET') {
        sendJson(response, 200, await listAdminNotificationBatches(getAdminToken(request), {
          search: url.searchParams.get('search') || '',
          status: url.searchParams.get('status') || '',
          page: url.searchParams.get('page') || '',
          pageSize: url.searchParams.get('pageSize') || url.searchParams.get('page_size') || '',
        }))
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminNotificationBatch(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminNotificationBatchSendMatch = path.match(/^\/api\/admin\/notification-batches\/([^/]+)\/send$/)
    if (adminNotificationBatchSendMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await sendAdminNotificationBatch(getAdminToken(request), decodeURIComponent(adminNotificationBatchSendMatch[1])))
      return
    }

    const adminNotificationBatchMatch = path.match(/^\/api\/admin\/notification-batches\/([^/]+)$/)
    if (adminNotificationBatchMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminNotificationBatch(getAdminToken(request), decodeURIComponent(adminNotificationBatchMatch[1])))
      return
    }

    if (path === '/api/admin/products') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminProducts(getAdminToken(request), {
            type: url.searchParams.get('type') || '',
            status: url.searchParams.get('status') || '',
            includeServiceTypes: url.searchParams.get('includeServiceTypes') === 'true' || url.searchParams.get('include_service_types') === 'true',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/event-registrations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminEventRegistrations(getAdminToken(request), {
          productId: url.searchParams.get('productId') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/course-registrations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminCourseRegistrations(getAdminToken(request), {
          productId: url.searchParams.get('productId') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/membership/plans') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminMembershipPlans(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminMembershipPlan(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/membership/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminMembershipCatalog(getAdminToken(request)))
      return
    }

    if (path === '/api/admin/membership/benefits') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminMembershipBenefits(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminMembershipBenefit(getAdminToken(request), '', await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminMembershipBenefitMatch = path.match(/^\/api\/admin\/membership\/benefits\/([^/]+)$/)
    if (adminMembershipBenefitMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminMembershipBenefit(
        getAdminToken(request),
        decodeURIComponent(adminMembershipBenefitMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminMembershipPlanBenefitsMatch = path.match(/^\/api\/admin\/membership\/plans\/([^/]+)\/benefits$/)
    if (adminMembershipPlanBenefitsMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminMembershipPlanBenefits(
        getAdminToken(request),
        decodeURIComponent(adminMembershipPlanBenefitsMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/membership/entitlements') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminMembershipEntitlements(getAdminToken(request), {
          search: url.searchParams.get('search') || '',
          benefitCode: url.searchParams.get('benefitCode') || url.searchParams.get('benefit_code') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminMembershipEntitlementAdjustMatch = path.match(/^\/api\/admin\/membership\/entitlements\/([^/]+)\/adjust$/)
    if (adminMembershipEntitlementAdjustMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await adjustAdminMembershipEntitlement(
        getAdminToken(request),
        decodeURIComponent(adminMembershipEntitlementAdjustMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/admin/membership/content-deliveries') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminMembershipContentDeliveries(getAdminToken(request), {
            status: url.searchParams.get('status') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminMembershipContentDelivery(getAdminToken(request), '', await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminMembershipContentDeliveryMatch = path.match(/^\/api\/admin\/membership\/content-deliveries\/([^/]+)$/)
    if (adminMembershipContentDeliveryMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminMembershipContentDelivery(
        getAdminToken(request),
        decodeURIComponent(adminMembershipContentDeliveryMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminMembershipPlanMatch = path.match(/^\/api\/admin\/membership\/plans\/([^/]+)$/)
    if (adminMembershipPlanMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminMembershipPlan(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminMembershipPlanMatch[1]),
      }))
      return
    }

    if (path === '/api/admin/agent-products') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminAgentProducts(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminAgentProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminAgentProductMatch = path.match(/^\/api\/admin\/agent-products\/([^/]+)$/)
    if (adminAgentProductMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminAgentProduct(getAdminToken(request), decodeURIComponent(adminAgentProductMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminAgentProduct(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminAgentProductMatch[1]),
      }))
      return
    }

    const adminAgentProductStatusMatch = path.match(/^\/api\/admin\/agent-products\/([^/]+)\/(publish|offline|draft)$/)
    if (adminAgentProductStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminAgentProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminAgentProductStatusMatch[1]),
          adminAgentProductStatusMatch[2] === 'publish' ? 'published' : adminAgentProductStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/course-products') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminCourseProducts(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminCourseProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminCourseProductRegistrationsMatch = path.match(/^\/api\/admin\/course-products\/([^/]+)\/registrations$/)
    if (adminCourseProductRegistrationsMatch) {
      if (method === 'POST') {
        sendJson(response, 201, await createStaffCourseRegistration(
          getAdminToken(request),
          decodeURIComponent(adminCourseProductRegistrationsMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminCourseRegistrations(getAdminToken(request), {
          productId: decodeURIComponent(adminCourseProductRegistrationsMatch[1]),
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminCourseProductMatch = path.match(/^\/api\/admin\/course-products\/([^/]+)$/)
    if (adminCourseProductMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminCourseProduct(getAdminToken(request), decodeURIComponent(adminCourseProductMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminCourseProduct(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminCourseProductMatch[1]),
      }))
      return
    }

    const adminCourseProductStatusMatch = path.match(/^\/api\/admin\/course-products\/([^/]+)\/(publish|offline|draft)$/)
    if (adminCourseProductStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminCourseProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminCourseProductStatusMatch[1]),
          adminCourseProductStatusMatch[2] === 'publish' ? 'published' : adminCourseProductStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/events') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminEventProducts(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminEventProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/event-options') {
      if (method === 'GET') {
        sendJson(response, 200, {
          optionSets: [
            { code: 'event_type', name: '展示类型', options: [
              { code: 'public', label: '公开活动', status: 'active', sortOrder: 10 },
              { code: 'free', label: '免费活动', status: 'active', sortOrder: 20 },
              { code: 'pro', label: '会员活动', status: 'active', sortOrder: 30 },
              { code: 'max', label: '高级会员活动', status: 'active', sortOrder: 40 },
            ] },
            { code: 'topic', name: '活动主题', options: ['峰会论坛', '政策研讨', 'AI应用', '数据安全', '企业参访'].map((label, index) => ({ code: label, label, status: 'active', sortOrder: (index + 1) * 10 })) },
            { code: 'event_format', name: '活动形式', options: ['线下活动', '线上活动', '工作坊', '参访交流'].map((label, index) => ({ code: label, label, status: 'active', sortOrder: (index + 1) * 10 })) },
          ],
        })
        return
      }
      if (method === 'PATCH') {
        await readJsonBody(request)
        sendJson(response, 200, { ok: true, message: '活动选项已接入语义接口；持久化字典将在独立迁移中启用。' })
        return
      }
      return methodNotAllowed(response)
    }

    const adminEventRegistrationsAliasMatch = path.match(/^\/api\/admin\/events\/([^/]+)\/registrations$/)
    if (adminEventRegistrationsAliasMatch) {
      if (method === 'POST') {
        sendJson(response, 201, await createStaffEventRegistration(
          getAdminToken(request),
          decodeURIComponent(adminEventRegistrationsAliasMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminEventRegistrations(getAdminToken(request), {
          productId: decodeURIComponent(adminEventRegistrationsAliasMatch[1]),
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminEventAliasMatch = path.match(/^\/api\/admin\/events\/([^/]+)$/)
    if (adminEventAliasMatch) {
      if (method === 'GET') {
        const items = await listAdminEventProducts(getAdminToken(request))
        const event = items.find((item) => item.id === decodeURIComponent(adminEventAliasMatch[1]) || item.slug === decodeURIComponent(adminEventAliasMatch[1]))
        if (!event) return notFound(response)
        sendJson(response, 200, event)
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminEventProduct(getAdminToken(request), decodeURIComponent(adminEventAliasMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminEventProduct(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminEventAliasMatch[1]),
      }))
      return
    }

    const adminEventAliasStatusMatch = path.match(/^\/api\/admin\/events\/([^/]+)\/(publish|offline|draft|close-registration)$/)
    if (adminEventAliasStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      const action = adminEventAliasStatusMatch[2]
      sendJson(
        response,
        200,
        await setAdminEventProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminEventAliasStatusMatch[1]),
          action === 'publish' ? 'published' : action === 'draft' ? 'draft' : action === 'close-registration' ? 'registration_closed' : 'offline',
        ),
      )
      return
    }

    const adminEventRegistrationCancelMatch = path.match(/^\/api\/admin\/event-registrations\/([^/]+)\/cancel$/)
    if (adminEventRegistrationCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelAdminEventRegistration(getAdminToken(request), decodeURIComponent(adminEventRegistrationCancelMatch[1]), await readJsonBody(request)))
      return
    }

    const adminEventRegistrationMatch = path.match(/^\/api\/admin\/event-registrations\/([^/]+)$/)
    if (adminEventRegistrationMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminEventRegistration(getAdminToken(request), decodeURIComponent(adminEventRegistrationMatch[1]), await readJsonBody(request)))
      return
    }

    if (path === '/api/admin/event-products') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminEventProducts(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminEventProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminEventProductRegistrationsMatch = path.match(/^\/api\/admin\/event-products\/([^/]+)\/registrations$/)
    if (adminEventProductRegistrationsMatch) {
      if (method === 'POST') {
        sendJson(response, 201, await createStaffEventRegistration(
          getAdminToken(request),
          decodeURIComponent(adminEventProductRegistrationsMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminEventRegistrations(getAdminToken(request), {
          productId: decodeURIComponent(adminEventProductRegistrationsMatch[1]),
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminEventProductMatch = path.match(/^\/api\/admin\/event-products\/([^/]+)$/)
    if (adminEventProductMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminEventProduct(getAdminToken(request), decodeURIComponent(adminEventProductMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminEventProduct(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminEventProductMatch[1]),
      }))
      return
    }

    const adminEventProductStatusMatch = path.match(/^\/api\/admin\/event-products\/([^/]+)\/(publish|offline|draft)$/)
    if (adminEventProductStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminEventProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminEventProductStatusMatch[1]),
          adminEventProductStatusMatch[2] === 'publish' ? 'published' : adminEventProductStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/data-service/page') {
      if (method === 'GET') {
        sendJson(response, 200, await getAdminDataServicePage(getAdminToken(request)))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminDataServicePage(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/data-service/requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminDataServiceRequests(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        scope: url.searchParams.get('scope') || 'all',
        keyword: url.searchParams.get('keyword') || url.searchParams.get('search') || '',
        assigneeId: url.searchParams.get('assigneeId') || '',
        departmentId: url.searchParams.get('departmentId') || '',
        dateFrom: url.searchParams.get('dateFrom') || '',
        dateTo: url.searchParams.get('dateTo') || '',
        page: url.searchParams.get('page') || 1,
        pageSize: url.searchParams.get('pageSize') || 50,
      }))
      return
    }

    if (path === '/api/admin/data-service/options') {
      if (method === 'GET') {
        sendJson(response, 200, { optionSets: await listAdminDataServiceOptions(getAdminToken(request)) })
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminDataServiceOptions(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/data-service/cases') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminDataCases(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminDataCase(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminDataServiceCaseMatch = path.match(/^\/api\/admin\/data-service\/cases\/([^/]+)$/)
    if (adminDataServiceCaseMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminDataProduct(getAdminToken(request), decodeURIComponent(adminDataServiceCaseMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminDataCase(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminDataServiceCaseMatch[1]),
      }))
      return
    }

    const adminDataServiceCaseStatusMatch = path.match(/^\/api\/admin\/data-service\/cases\/([^/]+)\/(publish|offline|draft)$/)
    if (adminDataServiceCaseStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminDataCaseStatus(
          getAdminToken(request),
          decodeURIComponent(adminDataServiceCaseStatusMatch[1]),
          adminDataServiceCaseStatusMatch[2] === 'publish' ? 'published' : adminDataServiceCaseStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/data-products') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminDataProducts(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminDataProduct(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/data-cases') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminDataCases(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAdminDataCase(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminDataProductMatch = path.match(/^\/api\/admin\/data-products\/([^/]+)$/)
    if (adminDataProductMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminDataProduct(getAdminToken(request), decodeURIComponent(adminDataProductMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminDataProduct(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminDataProductMatch[1]),
      }))
      return
    }

    const adminDataCaseMatch = path.match(/^\/api\/admin\/data-cases\/([^/]+)$/)
    if (adminDataCaseMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminDataProduct(getAdminToken(request), decodeURIComponent(adminDataCaseMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await upsertAdminDataCase(getAdminToken(request), {
        ...(await readJsonBody(request)),
        productId: decodeURIComponent(adminDataCaseMatch[1]),
      }))
      return
    }

    const adminDataProductStatusMatch = path.match(/^\/api\/admin\/data-products\/([^/]+)\/(publish|offline|draft)$/)
    if (adminDataProductStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminDataProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminDataProductStatusMatch[1]),
          adminDataProductStatusMatch[2] === 'publish' ? 'published' : adminDataProductStatusMatch[2],
        ),
      )
      return
    }

    const adminDataCaseStatusMatch = path.match(/^\/api\/admin\/data-cases\/([^/]+)\/(publish|offline|draft)$/)
    if (adminDataCaseStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminDataCaseStatus(
          getAdminToken(request),
          decodeURIComponent(adminDataCaseStatusMatch[1]),
          adminDataCaseStatusMatch[2] === 'publish' ? 'published' : adminDataCaseStatusMatch[2],
        ),
      )
      return
    }

    const adminProductMatch = path.match(/^\/api\/admin\/products\/([^/]+)$/)
    if (adminProductMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await updateAdminProduct(
          getAdminToken(request),
          decodeURIComponent(adminProductMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    const adminProductStatusMatch = path.match(/^\/api\/admin\/products\/([^/]+)\/(publish|offline)$/)
    if (adminProductStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminProductStatus(
          getAdminToken(request),
          decodeURIComponent(adminProductStatusMatch[1]),
          adminProductStatusMatch[2] === 'publish' ? 'published' : 'offline',
        ),
      )
      return
    }

    if (path === '/api/admin/news') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminNewsArticles(getAdminToken(request), {
            category: url.searchParams.get('category') || '',
            status: url.searchParams.get('status') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminNewsArticle(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/news-categories') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminNewsCategories(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminNewsCategory(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminNewsCategoryMatch = path.match(/^\/api\/admin\/news-categories\/([^/]+)$/)
    if (adminNewsCategoryMatch) {
      const code = decodeURIComponent(adminNewsCategoryMatch[1])
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminNewsCategory(getAdminToken(request), code, await readJsonBody(request)))
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminNewsCategory(getAdminToken(request), code))
        return
      }
      return methodNotAllowed(response)
    }

    const adminNewsMatch = path.match(/^\/api\/admin\/news\/([^/]+)$/)
    if (adminNewsMatch) {
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminNewsArticle(getAdminToken(request), decodeURIComponent(adminNewsMatch[1])))
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await updateAdminNewsArticle(
          getAdminToken(request),
          decodeURIComponent(adminNewsMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    const adminNewsStatusMatch = path.match(/^\/api\/admin\/news\/([^/]+)\/(publish|offline|draft)$/)
    if (adminNewsStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminNewsStatus(
          getAdminToken(request),
          decodeURIComponent(adminNewsStatusMatch[1]),
          adminNewsStatusMatch[2] === 'publish' ? 'published' : adminNewsStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/expert-applications') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminExpertApplications(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminExpertApplicationReviewMatch = path.match(/^\/api\/admin\/expert-applications\/([^/]+)\/review$/)
    if (adminExpertApplicationReviewMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await reviewAdminExpertApplication(
          getAdminToken(request),
          decodeURIComponent(adminExpertApplicationReviewMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    if (path === '/api/admin/expert-bookings') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminExpertBookings(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
          expertId: url.searchParams.get('expertId') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/expert-bookings/release-expired') {
      if (method !== 'POST') return methodNotAllowed(response)
      await requireAdmin(getAdminToken(request), 'expert_booking:update')
      sendJson(response, 200, await releaseExpiredExpertBookingHolds())
      return
    }

    const adminExpertBookingRescheduleMatch = path.match(/^\/api\/admin\/expert-bookings\/([^/]+)\/reschedules$/)
    if (adminExpertBookingRescheduleMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createExpertBookingReschedule(
        getAdminToken(request),
        decodeURIComponent(adminExpertBookingRescheduleMatch[1]),
        { ...(await readJsonBody(request)), admin: true },
      ))
      return
    }

    const adminExpertBookingRescheduleResponseMatch = path.match(/^\/api\/admin\/expert-bookings\/([^/]+)\/reschedules\/([^/]+)$/)
    if (adminExpertBookingRescheduleResponseMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await respondExpertBookingReschedule(
        getAdminToken(request),
        decodeURIComponent(adminExpertBookingRescheduleResponseMatch[1]),
        decodeURIComponent(adminExpertBookingRescheduleResponseMatch[2]),
        { ...(await readJsonBody(request)), admin: true },
      ))
      return
    }

    const adminExpertBookingStatusMatch = path.match(/^\/api\/admin\/expert-bookings\/([^/]+)$/)
    if (adminExpertBookingStatusMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateExpertBookingStatus(
        getAdminToken(request),
        decodeURIComponent(adminExpertBookingStatusMatch[1]),
        { ...(await readJsonBody(request)), admin: true },
      ))
      return
    }

    if (path === '/api/admin/expert-slots') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminExpertSlots(getAdminToken(request), {
            expertId: url.searchParams.get('expertId') || '',
            from: url.searchParams.get('from') || '',
            to: url.searchParams.get('to') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertExpertSlot(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/expert-withdrawals') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminExpertWithdrawals(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminExpertWithdrawalMatch = path.match(/^\/api\/admin\/expert-withdrawals\/([^/]+)$/)
    if (adminExpertWithdrawalMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminExpertWithdrawal(
        getAdminToken(request),
        decodeURIComponent(adminExpertWithdrawalMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminAgreementMatch = path.match(/^\/api\/admin\/site\/agreements\/([^/]+)$/)
    if (adminAgreementMatch) {
      if (method === 'GET') {
        await requireAdmin(getAdminToken(request), 'site:read')
        const item = await getAgreement(decodeURIComponent(adminAgreementMatch[1]), { includeDraft: true })
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminAgreement(
          getAdminToken(request),
          decodeURIComponent(adminAgreementMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/experts') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminExperts(getAdminToken(request), {
            status: url.searchParams.get('status') || '',
            direction: url.searchParams.get('direction') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminExpert(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminExpertMatch = path.match(/^\/api\/admin\/experts\/([^/]+)$/)
    if (adminExpertMatch) {
      if (method === 'GET') {
        const detail = await getAdminExpert(getAdminToken(request), decodeURIComponent(adminExpertMatch[1]))
        if (!detail) return notFound(response)
        sendJson(response, 200, detail)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminExpert(
          getAdminToken(request),
          decodeURIComponent(adminExpertMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminExpert(getAdminToken(request), decodeURIComponent(adminExpertMatch[1])))
        return
      }
      return methodNotAllowed(response)
    }

    const adminExpertStatusMatch = path.match(/^\/api\/admin\/experts\/([^/]+)\/(publish|offline|draft)$/)
    if (adminExpertStatusMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await setAdminExpertStatus(
          getAdminToken(request),
          decodeURIComponent(adminExpertStatusMatch[1]),
          adminExpertStatusMatch[2] === 'publish' ? 'published' : adminExpertStatusMatch[2],
        ),
      )
      return
    }

    if (path === '/api/admin/expert-directions') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAdminExpertDirections(getAdminToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminExpertDirection(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const adminExpertDirectionMatch = path.match(/^\/api\/admin\/expert-directions\/([^/]+)$/)
    if (adminExpertDirectionMatch) {
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminExpertDirection(
          getAdminToken(request),
          decodeURIComponent(adminExpertDirectionMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminExpertDirection(getAdminToken(request), decodeURIComponent(adminExpertDirectionMatch[1])))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/coupons') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAdminCoupons(getAdminToken(request), {
            status: url.searchParams.get('status') || '',
            discountType: url.searchParams.get('discountType') || '',
            search: url.searchParams.get('search') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createAdminCoupon(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/coupons/preview') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await previewAdminCoupon(getAdminToken(request), await readJsonBody(request)))
      return
    }

    const adminCouponRedemptionsMatch = path.match(/^\/api\/admin\/coupons\/([^/]+)\/redemptions$/)
    if (adminCouponRedemptionsMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminCouponRedemptions(getAdminToken(request), decodeURIComponent(adminCouponRedemptionsMatch[1])),
      })
      return
    }

    const adminCouponMatch = path.match(/^\/api\/admin\/coupons\/([^/]+)$/)
    if (adminCouponMatch) {
      if (method === 'GET') {
        sendJson(response, 200, await getAdminCoupon(getAdminToken(request), decodeURIComponent(adminCouponMatch[1])))
        return
      }
      if (method === 'PATCH') {
        sendJson(
          response,
          200,
          await updateAdminCoupon(
            getAdminToken(request),
            decodeURIComponent(adminCouponMatch[1]),
            await readJsonBody(request),
          ),
        )
        return
      }
      if (method === 'DELETE') {
        sendJson(response, 200, await deleteAdminCoupon(getAdminToken(request), decodeURIComponent(adminCouponMatch[1])))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/settlements') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminSettlements(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/orders') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminOrders(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
          search: url.searchParams.get('search') || '',
          from: url.searchParams.get('from') || '',
          to: url.searchParams.get('to') || '',
        }),
      })
      return
    }

    const adminOrderMatch = path.match(/^\/api\/admin\/orders\/([^/]+)$/)
    if (adminOrderMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const order = await getAdminOrder(getAdminToken(request), decodeURIComponent(adminOrderMatch[1]))
      if (!order) return notFound(response)
      sendJson(response, 200, order)
      return
    }

    if (path === '/api/admin/payments') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminPayments(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
          search: url.searchParams.get('search') || '',
          from: url.searchParams.get('from') || '',
          to: url.searchParams.get('to') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/dashboard/summary') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminDashboardSummary(getAdminToken(request), {
        range: url.searchParams.get('range') || '7d',
      }))
      return
    }

    if (path === '/api/admin/exceptions') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminOperationalEvents(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        severity: url.searchParams.get('severity') || '',
        type: url.searchParams.get('type') || '',
        q: url.searchParams.get('q') || url.searchParams.get('search') || '',
        page: url.searchParams.get('page') || '1',
      }))
      return
    }

    const adminExceptionActionMatch = path.match(/^\/api\/admin\/exceptions\/([^/]+)\/(retry|resolve)$/)
    if (adminExceptionActionMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      const eventId = decodeURIComponent(adminExceptionActionMatch[1])
      const body = await readJsonBody(request)
      sendJson(response, 200, adminExceptionActionMatch[2] === 'retry'
        ? await retryAdminOperationalEvent(getAdminToken(request), eventId, body)
        : await resolveAdminOperationalEvent(getAdminToken(request), eventId, body))
      return
    }

    const adminExceptionMatch = path.match(/^\/api\/admin\/exceptions\/([^/]+)$/)
    if (adminExceptionMatch) {
      const eventId = decodeURIComponent(adminExceptionMatch[1])
      if (method === 'GET') {
        const event = await getAdminOperationalEvent(getAdminToken(request), eventId)
        if (!event) return notFound(response)
        sendJson(response, 200, event)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminOperationalEvent(
          getAdminToken(request),
          eventId,
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/invoice-applications/export') {
      if (method !== 'GET') return methodNotAllowed(response)
      const rows = await listAdminInvoiceApplicationRows(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        q: url.searchParams.get('q') || url.searchParams.get('search') || '',
        from: url.searchParams.get('from') || '',
        to: url.searchParams.get('to') || '',
      })
      sendCsv(request, response, '发票申请导出.csv', rows, [
        ['申请单号', '申请单号'],
        ['订单号', '订单号'],
        ['结算编号', '结算编号'],
        ['手机号', '手机号'],
        ['金额', '金额'],
        ['发票抬头', '发票抬头'],
        ['税号', '税号'],
        ['接收邮箱', '接收邮箱'],
        ['状态', '状态'],
        ['发票号码', '发票号码'],
        ['申请时间', '申请时间'],
        ['开票时间', '开票时间'],
        ['原因', '原因'],
      ])
      return
    }

    if (path === '/api/admin/invoice-applications') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminInvoiceApplications(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        q: url.searchParams.get('q') || url.searchParams.get('search') || '',
        from: url.searchParams.get('from') || '',
        to: url.searchParams.get('to') || '',
        page: url.searchParams.get('page') || '1',
      }))
      return
    }

    const adminInvoiceFileMatch = path.match(/^\/api\/admin\/invoice-applications\/([^/]+)\/file$/)
    if (adminInvoiceFileMatch) {
      if (method === 'GET') {
        const invoice = await getAdminInvoiceApplication(getAdminToken(request), decodeURIComponent(adminInvoiceFileMatch[1]))
        if (!invoice?.pdfFileId) return notFound(response)
        const file = await getUploadedFile(invoice.pdfFileId)
        if (!file) return notFound(response)
        await sendUploadedFile(request, response, file)
        return
      }
      if (method !== 'POST') return methodNotAllowed(response)
      const storedFile = await saveRequestBodyToLocalBucket(
        request,
        decodeURIComponent(request.headers['x-file-name'] || 'invoice.pdf'),
      )
      sendJson(response, 201, await attachAdminInvoiceFile(
        getAdminToken(request),
        decodeURIComponent(adminInvoiceFileMatch[1]),
        {
          ...storedFile,
          mimeType: request.headers['content-type'] || 'application/octet-stream',
        },
      ))
      return
    }

    const adminInvoiceMatch = path.match(/^\/api\/admin\/invoice-applications\/([^/]+)$/)
    if (adminInvoiceMatch) {
      if (method === 'GET') {
        const invoice = await getAdminInvoiceApplication(getAdminToken(request), decodeURIComponent(adminInvoiceMatch[1]))
        if (!invoice) return notFound(response)
        sendJson(response, 200, invoice)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminInvoiceApplication(
          getAdminToken(request),
          decodeURIComponent(adminInvoiceMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/revenue') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAdminRevenueReport(getAdminToken(request), {
        from: url.searchParams.get('from') || '',
        to: url.searchParams.get('to') || '',
        type: url.searchParams.get('type') || '',
        status: url.searchParams.get('status') || '',
      }))
      return
    }

    if (path === '/api/admin/reconcile/export') {
      if (method !== 'GET') return methodNotAllowed(response)
      const from = url.searchParams.get('from') || ''
      const to = url.searchParams.get('to') || ''
      const rows = await listAdminReconcileRows(getAdminToken(request), {
        from,
        to,
        search: url.searchParams.get('search') || '',
      })
      const suffix = from || to ? `${from || '开始'}-${to || '至今'}` : '全部月份'
      sendCsv(request, response, `对账导出-${suffix}.csv`, rows)
      return
    }

    if (path === '/api/admin/reconcile') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminReconcileRows(getAdminToken(request), {
          from: url.searchParams.get('from') || '',
          to: url.searchParams.get('to') || '',
          search: url.searchParams.get('search') || '',
        }),
      })
      return
    }

    if (path === '/api/admin/business-search') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await searchAdminBusinessNumber(getAdminToken(request), url.searchParams.get('q') || ''),
      })
      return
    }

    if (path === '/api/admin/site/home') {
      if (method === 'GET') {
        await requireAdmin(getAdminToken(request), 'site:read')
        sendJson(response, 200, await getSiteHome({ includeHidden: true }))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminSiteHome(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/site/recommendation-slots') {
      if (method === 'GET') {
        sendJson(response, 200, await listAdminRecommendationSlots(getAdminToken(request), {
          placements: url.searchParams.get('placements') || url.searchParams.get('placement') || '',
        }))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminRecommendationSlots(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/site/recommendation-candidates') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminRecommendationCandidates(getAdminToken(request), {
        sourceType: url.searchParams.get('sourceType') || url.searchParams.get('source_type') || '',
        keyword: url.searchParams.get('keyword') || '',
        status: url.searchParams.get('status') || 'published',
      }))
      return
    }

    if (path === '/api/admin/site/about') {
      if (method === 'GET') {
        await requireAdmin(getAdminToken(request), 'site:read')
        sendJson(response, 200, await getSiteAbout({ includeHidden: true }))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminSiteAbout(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/site/consulting') {
      if (method === 'GET') {
        await requireAdmin(getAdminToken(request), 'site:read')
        sendJson(response, 200, await getSiteConsulting({ includeHidden: true }))
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminSiteConsulting(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/consulting-options') {
      if (method === 'GET') {
        sendJson(response, 200, { optionSets: await listAdminConsultingOptions(getAdminToken(request)) })
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminConsultingOptions(getAdminToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/consulting-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminConsultingRequests(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        scope: url.searchParams.get('scope') || 'all',
        keyword: url.searchParams.get('keyword') || '',
        assigneeId: url.searchParams.get('assigneeId') || '',
        ownerDepartment: url.searchParams.get('ownerDepartment') || url.searchParams.get('department') || '',
        page: url.searchParams.get('page') || '1',
        pageSize: url.searchParams.get('pageSize') || '20',
      }))
      return
    }

    const adminConsultingRequestCancelMatch = path.match(/^\/api\/admin\/consulting-requests\/([^/]+)\/cancel$/)
    if (adminConsultingRequestCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelAdminConsultingRequest(
        getAdminToken(request),
        decodeURIComponent(adminConsultingRequestCancelMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminConsultingRequestMatch = path.match(/^\/api\/admin\/consulting-requests\/([^/]+)$/)
    if (adminConsultingRequestMatch) {
      if (method === 'GET') {
        const item = await getAdminConsultingRequest(getAdminToken(request), decodeURIComponent(adminConsultingRequestMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminConsultingRequest(
          getAdminToken(request),
          decodeURIComponent(adminConsultingRequestMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/admin/cooperation-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminCooperationRequests(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const adminCooperationRequestConvertMatch = path.match(/^\/api\/admin\/cooperation-requests\/([^/]+)\/convert$/)
    if (adminCooperationRequestConvertMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await convertAdminCooperationRequest(
        getAdminToken(request),
        decodeURIComponent(adminCooperationRequestConvertMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminCooperationRequestCompleteMatch = path.match(/^\/api\/admin\/cooperation-requests\/([^/]+)\/complete$/)
    if (adminCooperationRequestCompleteMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await completeAdminCooperationRequest(getAdminToken(request), decodeURIComponent(adminCooperationRequestCompleteMatch[1])))
      return
    }

    const adminCooperationRequestMatch = path.match(/^\/api\/admin\/cooperation-requests\/([^/]+)$/)
    if (adminCooperationRequestMatch) {
      if (method === 'GET') {
        const item = await getAdminCooperationRequest(getAdminToken(request), decodeURIComponent(adminCooperationRequestMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method === 'PATCH') {
        sendJson(response, 200, await updateAdminCooperationRequest(
          getAdminToken(request),
          decodeURIComponent(adminCooperationRequestMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/products') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listProducts(url.searchParams.get('type') || ''),
      })
      return
    }

    if (path === '/api/ai/wechat/assist') {
      if (method !== 'POST') return methodNotAllowed(response)
      enforceMemoryRateLimit(request, 'ai:wechat-assist', { limit: 90, windowMs: 60_000 })
      sendJson(response, 200, await createWechatAiAssist(await readJsonBody(request), {
        token: getBearerToken(request),
      }))
      return
    }

    if (path === '/api/site/home') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getSiteHome())
      return
    }

    if (path === '/api/site/recommendations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getSiteRecommendations(url.searchParams.get('placements') || url.searchParams.get('placement') || ''))
      return
    }

    if (path === '/api/site/about') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getSiteAbout())
      return
    }

    if (path === '/api/site/consulting') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getSiteConsulting())
      return
    }

    if (path === '/api/data-service/page') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getDataServicePage())
      return
    }

    if (path === '/api/data-service/options') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { optionSets: await listDataServiceOptions() })
      return
    }

    const agreementMatch = path.match(/^\/api\/site\/agreements\/([^/]+)$/)
    if (agreementMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const item = await getAgreement(decodeURIComponent(agreementMatch[1]))
      if (!item) return notFound(response)
      sendJson(response, 200, item)
      return
    }

    if (path === '/api/expert-directions') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listExpertDirections() })
      return
    }

    if (path === '/api/membership/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getMembershipCatalog())
      return
    }

    if (path === '/api/agents/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAgentCatalog())
      return
    }

    if (path.startsWith('/api/agents/catalog/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const agent = await getAgentProduct(decodeURIComponent(path.replace('/api/agents/catalog/', '')))
      if (!agent) return notFound(response)
      sendJson(response, 200, agent)
      return
    }

    if (path === '/api/data/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listDataCatalog())
      return
    }

    if (path.startsWith('/api/data/catalog/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const product = await getDataProduct(decodeURIComponent(path.replace('/api/data/catalog/', '')))
      if (!product) return notFound(response)
      sendJson(response, 200, product)
      return
    }

    if (path === '/api/courses/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listCourseCatalog())
      return
    }

    if (path.startsWith('/api/courses/catalog/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const course = await getCourseProduct(decodeURIComponent(path.replace('/api/courses/catalog/', '')))
      if (!course) return notFound(response)
      sendJson(response, 200, course)
      return
    }

    if (path === '/api/events/catalog') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listEventCatalog())
      return
    }

    if (path.startsWith('/api/events/catalog/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const event = await getEventProduct(decodeURIComponent(path.replace('/api/events/catalog/', '')))
      if (!event) return notFound(response)
      sendJson(response, 200, event)
      return
    }

    if (path === '/api/news') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listNewsArticles({
          category: url.searchParams.get('category') || '',
        }),
      })
      return
    }

    if (path === '/api/news-categories') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listNewsCategories() })
      return
    }

    if (path === '/api/news/featured') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listFeaturedNewsArticles() })
      return
    }

    if (path === '/api/experts') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listExperts({
          specialty: url.searchParams.get('specialty') || '',
          direction: url.searchParams.get('direction') || '',
          search: url.searchParams.get('search') || '',
          available: url.searchParams.get('available') || '',
        }),
      })
      return
    }

    const expertSlotsMatch = path.match(/^\/api\/experts\/([^/]+)\/slots$/)
    if (expertSlotsMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listExpertSlots(decodeURIComponent(expertSlotsMatch[1]), {
          from: url.searchParams.get('from') || '',
          to: url.searchParams.get('to') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path.startsWith('/api/experts/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const expert = await getExpert(decodeURIComponent(path.replace('/api/experts/', '')))
      if (!expert) return notFound(response)
      sendJson(response, 200, expert)
      return
    }

    if (path.startsWith('/api/news/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const article = await getNewsArticle(decodeURIComponent(path.replace('/api/news/', '')))
      if (!article) return notFound(response)
      sendJson(response, 200, article)
      return
    }

    if (path.startsWith('/api/products/')) {
      if (method !== 'GET') return methodNotAllowed(response)
      const product = await getProduct(decodeURIComponent(path.replace('/api/products/', '')))
      if (!product) return notFound(response)
      sendJson(response, 200, product)
      return
    }

    if (path === '/api/checkout/preview') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await previewCheckout(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/orders') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createOrder(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/payment-orders') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createPaymentOrder(getBearerToken(request), await readJsonBody(request)))
      return
    }

    const paymentStatusMatch = path.match(/^\/api\/payment-orders\/([^/]+)\/status$/)
    if (paymentStatusMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getPaymentStatus(getBearerToken(request), decodeURIComponent(paymentStatusMatch[1])))
      return
    }

    const paymentCancelMatch = path.match(/^\/api\/payment-orders\/([^/]+)\/cancel$/)
    if (paymentCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelPaymentOrder(getBearerToken(request), decodeURIComponent(paymentCancelMatch[1])))
      return
    }

    if (path === '/api/payments/wechat/notify') {
      if (method !== 'POST') return methodNotAllowed(response)
      await handleWechatPayNotify(request.headers, await readRawBody(request))
      sendJson(response, 200, { code: 'SUCCESS', message: '成功' })
      return
    }

    const devPaymentMatch = path.match(/^\/api\/dev\/payment-orders\/([^/]+)\/succeed$/)
    if (devPaymentMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await succeedDevPayment(getAdminToken(request), decodeURIComponent(devPaymentMatch[1])))
      return
    }

    if (path === '/api/account/orders') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountOrders(getBearerToken(request)),
      })
      return
    }

    const accountOrderMatch = path.match(/^\/api\/account\/orders\/([^/]+)$/)
    if (accountOrderMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const order = await getAccountOrder(getBearerToken(request), decodeURIComponent(accountOrderMatch[1]))
      if (!order) return notFound(response)
      sendJson(response, 200, order)
      return
    }

    const accountOrderInvoiceMatch = path.match(/^\/api\/account\/orders\/([^/]+)\/invoice-application$/)
    if (accountOrderInvoiceMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createAccountInvoiceApplication(
        getBearerToken(request),
        decodeURIComponent(accountOrderInvoiceMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/account/invoice-applications') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountInvoiceApplications(getBearerToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const accountInvoiceFileMatch = path.match(/^\/api\/account\/invoice-applications\/([^/]+)\/file$/)
    if (accountInvoiceFileMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const invoice = await getAccountInvoiceApplication(getBearerToken(request), decodeURIComponent(accountInvoiceFileMatch[1]))
      if (!invoice?.pdfFileId) return notFound(response)
      const file = await getUploadedFile(invoice.pdfFileId)
      if (!file) return notFound(response)
      await sendUploadedFile(request, response, file)
      return
    }

    const accountInvoiceMatch = path.match(/^\/api\/account\/invoice-applications\/([^/]+)$/)
    if (accountInvoiceMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const invoice = await getAccountInvoiceApplication(getBearerToken(request), decodeURIComponent(accountInvoiceMatch[1]))
      if (!invoice) return notFound(response)
      sendJson(response, 200, invoice)
      return
    }

    if (path === '/api/account/expert-application') {
      if (method === 'GET') {
        sendJson(response, 200, await getAccountExpertApplication(getBearerToken(request)) || null)
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await submitExpertApplication(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/account/expert-profile') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAccountExpertProfile(getBearerToken(request)) || null)
      return
    }

    if (path === '/api/account/expert-profile/accepting') {
      if (method !== 'PATCH') return methodNotAllowed(response)
      const body = await readJsonBody(request)
      sendJson(response, 200, await setAccountExpertAccepting(getBearerToken(request), Boolean(body.accepting)))
      return
    }

    if (path === '/api/account/expert-bookings') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listAccountExpertBookings(getBearerToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createExpertBooking(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    const accountExpertBookingMatch = path.match(/^\/api\/account\/expert-bookings\/([^/]+)$/)
    if (accountExpertBookingMatch) {
      if (method === 'GET') {
        const booking = await getAccountExpertBooking(getBearerToken(request), decodeURIComponent(accountExpertBookingMatch[1]))
        if (!booking) return notFound(response)
        sendJson(response, 200, booking)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateExpertBookingStatus(
        getBearerToken(request),
        decodeURIComponent(accountExpertBookingMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const accountExpertBookingConfirmMatch = path.match(/^\/api\/account\/expert-bookings\/([^/]+)\/confirm-completion$/)
    if (accountExpertBookingConfirmMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await confirmAccountExpertBookingCompletion(
        getBearerToken(request),
        decodeURIComponent(accountExpertBookingConfirmMatch[1]),
      ))
      return
    }

    const accountExpertBookingDisputeMatch = path.match(/^\/api\/account\/expert-bookings\/([^/]+)\/dispute$/)
    if (accountExpertBookingDisputeMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await disputeAccountExpertBookingCompletion(
        getBearerToken(request),
        decodeURIComponent(accountExpertBookingDisputeMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const accountExpertBookingRescheduleMatch = path.match(/^\/api\/account\/expert-bookings\/([^/]+)\/reschedules$/)
    if (accountExpertBookingRescheduleMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createExpertBookingReschedule(
        getBearerToken(request),
        decodeURIComponent(accountExpertBookingRescheduleMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const accountExpertBookingRescheduleResponseMatch = path.match(/^\/api\/account\/expert-bookings\/([^/]+)\/reschedules\/([^/]+)$/)
    if (accountExpertBookingRescheduleResponseMatch) {
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await respondExpertBookingReschedule(
        getBearerToken(request),
        decodeURIComponent(accountExpertBookingRescheduleResponseMatch[1]),
        decodeURIComponent(accountExpertBookingRescheduleResponseMatch[2]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/account/expert-slots') {
      if (method === 'GET') {
        sendJson(response, 200, {
          items: await listAccountExpertSlots(getBearerToken(request), {
            from: url.searchParams.get('from') || '',
            to: url.searchParams.get('to') || '',
          }),
        })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await upsertAccountExpertSlot(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/account/expert-wallet') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await getAccountExpertWallet(getBearerToken(request)))
      return
    }

    if (path === '/api/account/expert-withdrawals') {
      if (method === 'GET') {
        sendJson(response, 200, { items: await listExpertWithdrawals(getBearerToken(request)) })
        return
      }
      if (method === 'POST') {
        sendJson(response, 201, await createExpertWithdrawal(getBearerToken(request), await readJsonBody(request)))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/account/data-products') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountDataProducts(getBearerToken(request)),
      })
      return
    }

    if (path === '/api/admin/data-service-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, await listAdminDataServiceRequests(getAdminToken(request), {
        status: url.searchParams.get('status') || '',
        scope: url.searchParams.get('scope') || '',
        keyword: url.searchParams.get('keyword') || url.searchParams.get('search') || '',
        assigneeId: url.searchParams.get('assigneeId') || '',
        departmentId: url.searchParams.get('departmentId') || '',
        dateFrom: url.searchParams.get('dateFrom') || '',
        dateTo: url.searchParams.get('dateTo') || '',
        page: url.searchParams.get('page') || '',
        pageSize: url.searchParams.get('pageSize') || '',
      }))
      return
    }

    const adminDataServiceCancelMatch = path.match(/^\/api\/admin\/data-service-requests\/([^/]+)\/cancel$/)
    if (adminDataServiceCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelAdminDataServiceRequest(
        getAdminToken(request),
        decodeURIComponent(adminDataServiceCancelMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminDataServiceRequestAliasCancelMatch = path.match(/^\/api\/admin\/data-service\/requests\/([^/]+)\/cancel$/)
    if (adminDataServiceRequestAliasCancelMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await cancelAdminDataServiceRequest(
        getAdminToken(request),
        decodeURIComponent(adminDataServiceRequestAliasCancelMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminDataServiceRequestAliasMatch = path.match(/^\/api\/admin\/data-service\/requests\/([^/]+)$/)
    if (adminDataServiceRequestAliasMatch) {
      if (method === 'GET') {
        const item = await getAdminDataServiceRequest(getAdminToken(request), decodeURIComponent(adminDataServiceRequestAliasMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminDataServiceRequest(
        getAdminToken(request),
        decodeURIComponent(adminDataServiceRequestAliasMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const adminDataServiceMatch = path.match(/^\/api\/admin\/data-service-requests\/([^/]+)$/)
    if (adminDataServiceMatch) {
      if (method === 'GET') {
        const item = await getAdminDataServiceRequest(getAdminToken(request), decodeURIComponent(adminDataServiceMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(response, 200, await updateAdminDataServiceRequest(
        getAdminToken(request),
        decodeURIComponent(adminDataServiceMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/data-service-requests') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createDataServiceRequest(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/data-service-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountDataServiceRequests(getBearerToken(request)),
      })
      return
    }

    const accountDataServiceCheckoutMatch = path.match(/^\/api\/account\/data-service-requests\/([^/]+)\/checkout$/)
    if (accountDataServiceCheckoutMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createDataServiceCheckout(
        getBearerToken(request),
        decodeURIComponent(accountDataServiceCheckoutMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    const accountDataServiceMatch = path.match(/^\/api\/account\/data-service-requests\/([^/]+)$/)
    if (accountDataServiceMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const item = await getAccountDataServiceRequest(getBearerToken(request), decodeURIComponent(accountDataServiceMatch[1]))
      if (!item) return notFound(response)
      sendJson(response, 200, item)
      return
    }

    if (path === '/api/account/event-registrations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountEventRegistrations(getBearerToken(request)),
      })
      return
    }

    if (path === '/api/account/course-registrations') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountCourseRegistrations(getBearerToken(request)),
      })
      return
    }

    const accountCourseRegistrationMatch = path.match(/^\/api\/account\/course-registrations\/([^/]+)$/)
    if (accountCourseRegistrationMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const registration = await getAccountCourseRegistration(getBearerToken(request), decodeURIComponent(accountCourseRegistrationMatch[1]))
      if (!registration) return notFound(response)
      sendJson(response, 200, registration)
      return
    }

    const accountEventRegistrationMatch = path.match(/^\/api\/account\/event-registrations\/([^/]+)$/)
    if (accountEventRegistrationMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const registration = await getAccountEventRegistration(getBearerToken(request), decodeURIComponent(accountEventRegistrationMatch[1]))
      if (!registration) return notFound(response)
      sendJson(response, 200, registration)
      return
    }

    if (path === '/api/account/entitlements') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountEntitlements(getBearerToken(request)),
      })
      return
    }

    if (path === '/api/consulting-requests') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createConsultingRequest(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/cooperation-requests') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createCooperationRequest(getBearerToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/account/consulting-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountConsultingRequests(getBearerToken(request)),
      })
      return
    }

    const accountConsultingCheckoutMatch = path.match(/^\/api\/account\/consulting-requests\/([^/]+)\/checkout$/)
    if (accountConsultingCheckoutMatch) {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 201, await createConsultingCheckout(
        getBearerToken(request),
        decodeURIComponent(accountConsultingCheckoutMatch[1]),
        await readJsonBody(request),
      ))
      return
    }

    if (path === '/api/account/tasks') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAccountTasks(getBearerToken(request), {
          type: url.searchParams.get('type') || '',
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const accountTaskMatch = path.match(/^\/api\/account\/tasks\/([^/]+)$/)
    if (accountTaskMatch) {
      if (method !== 'GET') return methodNotAllowed(response)
      const task = await getAccountTask(getBearerToken(request), decodeURIComponent(accountTaskMatch[1]))
      if (!task) return notFound(response)
      sendJson(response, 200, task)
      return
    }

    const accountTaskMaterialsMatch = path.match(/^\/api\/account\/tasks\/([^/]+)\/materials$/)
    if (accountTaskMaterialsMatch) {
      if (method !== 'PATCH' && method !== 'POST') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await submitAccountTaskMaterials(
          getBearerToken(request),
          decodeURIComponent(accountTaskMaterialsMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    if (path === '/api/staff/tasks') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffTasks(getAdminToken(request), {
          type: url.searchParams.get('type') || '',
          status: url.searchParams.get('status') || '',
          scope: url.searchParams.get('scope') || '',
          keyword: url.searchParams.get('keyword') || '',
        }),
      })
      return
    }

    if (path === '/api/staff/orders') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listAdminOrders(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    if (path === '/api/staff/data-service-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffDataServiceRequests(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
          scope: url.searchParams.get('scope') || '',
          keyword: url.searchParams.get('keyword') || '',
        }),
      })
      return
    }

    const staffDataServiceMatch = path.match(/^\/api\/staff\/data-service-requests\/([^/]+)$/)
    if (staffDataServiceMatch) {
      if (method === 'GET') {
        const item = await getStaffDataServiceRequest(getAdminToken(request), decodeURIComponent(staffDataServiceMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await updateStaffDataServiceRequest(
          getAdminToken(request),
          decodeURIComponent(staffDataServiceMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    if (path === '/api/staff/events') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listStaffEventProducts(getAdminToken(request)) })
      return
    }

    if (path === '/api/staff/courses') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, { items: await listStaffCourseProducts(getAdminToken(request)) })
      return
    }

    const staffCourseRegistrationsMatch = path.match(/^\/api\/staff\/courses\/([^/]+)\/registrations$/)
    if (staffCourseRegistrationsMatch) {
      if (method === 'POST') {
        sendJson(response, 201, await createStaffCourseRegistration(
          getAdminToken(request),
          decodeURIComponent(staffCourseRegistrationsMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffCourseRegistrations(getAdminToken(request), {
          productId: decodeURIComponent(staffCourseRegistrationsMatch[1]),
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const staffCourseRegistrationMatch = path.match(/^\/api\/staff\/course-registrations\/([^/]+)$/)
    if (staffCourseRegistrationMatch) {
      if (method === 'GET') {
        const registration = await getStaffCourseRegistration(getAdminToken(request), decodeURIComponent(staffCourseRegistrationMatch[1]))
        if (!registration) return notFound(response)
        sendJson(response, 200, registration)
        return
      }
      if (method === 'POST') {
        sendJson(response, 200, await checkInCourseRegistrationById(
          getAdminToken(request),
          decodeURIComponent(staffCourseRegistrationMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/staff/course-checkins/scan') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await checkInCourseRegistrationByCode(getAdminToken(request), await readJsonBody(request)))
      return
    }

    const staffEventRegistrationsMatch = path.match(/^\/api\/staff\/events\/([^/]+)\/registrations$/)
    if (staffEventRegistrationsMatch) {
      if (method === 'POST') {
        sendJson(response, 201, await createStaffEventRegistration(
          getAdminToken(request),
          decodeURIComponent(staffEventRegistrationsMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffEventRegistrations(getAdminToken(request), {
          productId: decodeURIComponent(staffEventRegistrationsMatch[1]),
          status: url.searchParams.get('status') || '',
        }),
      })
      return
    }

    const staffEventRegistrationMatch = path.match(/^\/api\/staff\/event-registrations\/([^/]+)$/)
    if (staffEventRegistrationMatch) {
      if (method === 'GET') {
        const registration = await getStaffEventRegistration(getAdminToken(request), decodeURIComponent(staffEventRegistrationMatch[1]))
        if (!registration) return notFound(response)
        sendJson(response, 200, registration)
        return
      }
      if (method === 'POST') {
        sendJson(response, 200, await checkInEventRegistrationById(
          getAdminToken(request),
          decodeURIComponent(staffEventRegistrationMatch[1]),
          await readJsonBody(request),
        ))
        return
      }
      return methodNotAllowed(response)
    }

    if (path === '/api/staff/event-checkins/scan') {
      if (method !== 'POST') return methodNotAllowed(response)
      sendJson(response, 200, await checkInEventRegistrationByCode(getAdminToken(request), await readJsonBody(request)))
      return
    }

    if (path === '/api/staff/consulting-requests') {
      if (method !== 'GET') return methodNotAllowed(response)
      sendJson(response, 200, {
        items: await listStaffConsultingRequests(getAdminToken(request), {
          status: url.searchParams.get('status') || '',
          scope: url.searchParams.get('scope') || '',
          keyword: url.searchParams.get('keyword') || '',
        }),
      })
      return
    }

    const staffConsultingMatch = path.match(/^\/api\/staff\/consulting-requests\/([^/]+)$/)
    if (staffConsultingMatch) {
      if (method === 'GET') {
        const item = await getStaffConsultingRequest(getAdminToken(request), decodeURIComponent(staffConsultingMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await updateStaffConsultingRequest(
          getAdminToken(request),
          decodeURIComponent(staffConsultingMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    const staffTaskMatch = path.match(/^\/api\/staff\/tasks\/([^/]+)$/)
    if (staffTaskMatch) {
      if (method === 'GET') {
        const item = await getStaffTask(getAdminToken(request), decodeURIComponent(staffTaskMatch[1]))
        if (!item) return notFound(response)
        sendJson(response, 200, item)
        return
      }
      if (method !== 'PATCH') return methodNotAllowed(response)
      sendJson(
        response,
        200,
        await updateStaffTask(
          getAdminToken(request),
          decodeURIComponent(staffTaskMatch[1]),
          await readJsonBody(request),
        ),
      )
      return
    }

    notFound(response)
  } catch (error) {
    const headers = error.retryAfter ? { 'retry-after': String(error.retryAfter) } : {}
    const statusCode = error.statusCode || 500
    if (statusCode >= 500 && /(upload|file|invoice-applications\/[^/]+\/file)/.test(path)) {
      try {
        incrementMetric('dlbdi_file_operations_total', { status: 'failed', route: path.includes('invoice-applications') ? 'invoice_file' : 'upload' })
        await recordOperationalEvent({
          severity: 'error',
          eventType: 'file.operation.failed',
          resourceType: 'api_route',
          resourceId: path,
          message: error.message || '文件操作失败',
          payload: {
            code: error.code || 'file_operation_failed',
            method,
            requestId: request.requestId,
          },
        })
      } catch {}
    }
    const eventId = statusCode >= 500
      ? await captureException(error, {
          requestId: request.requestId,
          method,
          route: path,
        })
      : ''
    sendJson(response, statusCode, {
      error: error.code || 'internal_error',
      message: error.message || 'Internal server error',
      ...(eventId ? { eventId } : {}),
      ...(error.retryAfter ? { retryAfter: error.retryAfter } : {}),
    }, headers)
  }
}
