import { Router } from 'express'

import { createRateLimitMiddleware, getBodyFieldRateLimitKey } from '../middleware/rate-limit.js'
import { uploadSingleFile } from './file-upload.js'
import { uploadFileAsset } from '../services/file-storage/file-storage-service.js'
import {
  cancelWorkerOrder,
  changeWorkerPassword,
  createWorkerRechargeRequest,
  createWorkerWithdrawRequest,
  getWorkerProfile,
  getWorkerSessionSummary,
  grabWorkerHallOrder,
  joinWorkerSharingOrder,
  listWorkerProfileFinanceRequests,
  listWorkerProfileWalletLedgers,
  listWorkerHallOrders,
  listWorkerMyOrders,
  loginWorker,
  logoutWorkerSession,
  registerWorker,
  sendWorkerSmsCode,
  submitWorkerOrderAcceptance,
} from '../services/worker-platform/index.js'
import { buildNotFoundPayload, createRouteHandler } from '../utils/http.js'
import {
  extractOptionalWorkerBearerToken,
  extractWorkerBearerToken,
  getRequiredWorkerSession,
  requireActiveWorker,
  requireWorkerSession,
} from './worker/session.js'

const router = Router()

router.post(
  '/auth/sms-code',
  createRateLimitMiddleware({
    scope: 'worker:sms-code',
    windowMs: 60_000,
    max: 5,
    key: getBodyFieldRateLimitKey('phone'),
  }),
  createRouteHandler((req) => sendWorkerSmsCode(req.body || {}), {
    successMessage: '验证码已发送',
    errorMessage: '验证码发送失败',
    scope: '[worker/auth/sms-code]',
  }),
)

router.post(
  '/auth/register',
  createRateLimitMiddleware({
    scope: 'worker:register',
    windowMs: 60_000,
    max: 5,
    key: getBodyFieldRateLimitKey('phone'),
  }),
  createRouteHandler((req) => registerWorker(req.body || {}), {
    successMessage: '注册成功，请使用手机号登录',
    errorMessage: '接单账号注册失败',
    scope: '[worker/auth/register]',
  }),
)

router.post(
  '/auth/login',
  createRateLimitMiddleware({
    scope: 'worker:login',
    windowMs: 60_000,
    max: 10,
    key: getBodyFieldRateLimitKey('username'),
  }),
  createRouteHandler((req) => loginWorker(req.body?.username, req.body?.password), {
    successMessage: '登录成功',
    errorMessage: '接单端登录失败',
    scope: '[worker/auth/login]',
  }),
)

router.get(
  '/auth/session',
  createRouteHandler((req) => getWorkerSessionSummary(extractWorkerBearerToken(req)), {
    successMessage: 'ok',
    errorMessage: '读取接单登录态失败',
    scope: '[worker/auth/session]',
  }),
)

router.post(
  '/auth/logout',
  createRouteHandler((req) => logoutWorkerSession(extractOptionalWorkerBearerToken(req)), {
    successMessage: '已退出登录',
    errorMessage: '退出失败',
    scope: '[worker/auth/logout]',
  }),
)

router.use(requireWorkerSession)

router.get(
  '/profile',
  createRouteHandler((req) => getWorkerProfile(getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取打手信息失败',
    scope: '[worker/profile]',
  }),
)

router.get(
  '/profile/wallet-ledgers',
  createRouteHandler((req) => listWorkerProfileWalletLedgers(req.query, getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取钱包流水失败',
    scope: '[worker/profile/wallet-ledgers]',
  }),
)

router.get(
  '/profile/finance-requests',
  createRouteHandler((req) => listWorkerProfileFinanceRequests(req.query, getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取资金申请记录失败',
    scope: '[worker/profile/finance-requests]',
  }),
)

router.post(
  '/profile/recharge-requests',
  requireActiveWorker,
  createRouteHandler((req) => createWorkerRechargeRequest(req.body || {}, getRequiredWorkerSession(req)), {
    successMessage: '充值申请已提交',
    errorMessage: '提交充值申请失败',
    scope: '[worker/profile/recharge-requests]',
  }),
)

router.post(
  '/profile/withdraw-requests',
  requireActiveWorker,
  createRouteHandler((req) => createWorkerWithdrawRequest(req.body || {}, getRequiredWorkerSession(req)), {
    successMessage: '提现申请已提交',
    errorMessage: '提交提现申请失败',
    scope: '[worker/profile/withdraw-requests]',
  }),
)

router.post(
  '/profile/change-password',
  createRouteHandler((req) => changeWorkerPassword(req.body || {}, getRequiredWorkerSession(req)), {
    successMessage: '密码已修改',
    errorMessage: '修改密码失败',
    scope: '[worker/profile/change-password]',
  }),
)

router.post(
  '/files/upload',
  requireActiveWorker,
  uploadSingleFile,
  createRouteHandler(
    (req) => {
      const session = getRequiredWorkerSession(req)
      return uploadFileAsset({
        file: req.file,
        scene: req.body?.scene || 'worker-acceptance',
        uploaderType: 'worker',
        uploaderId: String(session.workerId),
      })
    },
    {
      successMessage: '文件已上传',
      errorMessage: '文件上传失败',
      scope: '[worker/files/upload]',
    },
  ),
)

router.get(
  '/hall/orders',
  requireActiveWorker,
  createRouteHandler((req) => listWorkerHallOrders(req.query, getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取抢单大厅失败',
    scope: '[worker/hall/orders]',
  }),
)

router.post(
  '/hall/orders/:workOrderId/grab',
  requireActiveWorker,
  createRouteHandler(
    (req) =>
      grabWorkerHallOrder(String(req.params.workOrderId || ''), getRequiredWorkerSession(req)),
    {
      successMessage: '抢单成功',
      errorMessage: '抢单失败',
      scope: '[worker/hall/orders/:workOrderId/grab]',
    },
  ),
)

router.post(
  '/hall/orders/:workOrderId/join-sharing',
  requireActiveWorker,
  createRouteHandler(
    (req) =>
      joinWorkerSharingOrder(
        String(req.params.workOrderId || ''),
        req.body || {},
        getRequiredWorkerSession(req),
      ),
    {
      successMessage: '拼单成功',
      errorMessage: '拼单失败',
      scope: '[worker/hall/orders/:workOrderId/join-sharing]',
    },
  ),
)

router.get(
  '/orders',
  requireActiveWorker,
  createRouteHandler((req) => listWorkerMyOrders(req.query, getRequiredWorkerSession(req)), {
    successMessage: 'ok',
    errorMessage: '读取我的订单失败',
    scope: '[worker/orders]',
  }),
)

router.post(
  '/orders/:workOrderId/submit-acceptance',
  requireActiveWorker,
  createRouteHandler(
    (req) =>
      submitWorkerOrderAcceptance(
        String(req.params.workOrderId || ''),
        req.body || {},
        getRequiredWorkerSession(req),
      ),
    {
      successMessage: '验收资料已提交',
      errorMessage: '提交验收资料失败',
      scope: '[worker/orders/:workOrderId/submit-acceptance]',
    },
  ),
)

router.post(
  '/orders/:workOrderId/cancel',
  requireActiveWorker,
  createRouteHandler(
    (req) => cancelWorkerOrder(String(req.params.workOrderId || ''), getRequiredWorkerSession(req)),
    {
      successMessage: '已取消接单',
      errorMessage: '取消接单失败',
      scope: '[worker/orders/:workOrderId/cancel]',
    },
  ),
)

router.use((req, res) => {
  res.status(404).json(buildNotFoundPayload(req))
})

export default router
