import { Router } from 'express'

import { createRateLimitMiddleware, getBodyFieldRateLimitKey } from '../../middleware/rate-limit.js'
import {
  deleteWorkerSessionWithCredentials,
  getWorkerSessionSummary,
  loginWorker,
  loginWorkerBySmsCode,
  logoutWorkerSession,
  manageWorkerSessions,
  registerWorker,
  resetWorkerPassword,
  sendWorkerLoginSmsCode,
  sendWorkerPasswordResetSmsCode,
  sendWorkerSmsCode,
} from '../../services/worker-platform/index.js'
import { extractOptionalWorkerBearerToken, extractWorkerBearerToken } from './session.js'
import { createRouteHandler } from '../../utils/http.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/password-reset/sms-code',
  createRateLimitMiddleware({
    scope: 'worker:password-reset-sms-code',
    windowMs: 60_000,
    max: 5,
    key: getBodyFieldRateLimitKey('phone'),
  }),
  createRouteHandler((req) => sendWorkerPasswordResetSmsCode(req.body || {}), {
    successMessage: '验证码已发送',
    errorMessage: '验证码发送失败',
    scope: '[worker/auth/password-reset/sms-code]',
  }),
)

router.post(
  '/auth/password-reset',
  createRateLimitMiddleware({
    scope: 'worker:password-reset',
    windowMs: 60_000,
    max: 10,
    key: getBodyFieldRateLimitKey('phone'),
  }),
  createRouteHandler((req) => resetWorkerPassword(req.body || {}), {
    successMessage: '密码已重置，请重新登录',
    errorMessage: '密码重置失败',
    scope: '[worker/auth/password-reset]',
  }),
)

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, {
        deviceId: req.body?.deviceId,
        deviceType: req.body?.deviceType,
        deviceName: req.body?.deviceName,
        userAgent: req.headers['user-agent'],
        ipAddress: req.ip,
      }),
    {
      successMessage: '登录成功',
      errorMessage: '接单端登录失败',
      scope: '[worker/auth/login]',
    },
  ),
)

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

router.post(
  '/auth/login/sms',
  createRateLimitMiddleware({
    scope: 'worker:login-sms',
    windowMs: 60_000,
    max: 10,
    key: getBodyFieldRateLimitKey('phone'),
  }),
  createRouteHandler(
    (req) =>
      loginWorkerBySmsCode(req.body?.phone, req.body?.code, {
        deviceId: req.body?.deviceId,
        deviceType: req.body?.deviceType,
        deviceName: req.body?.deviceName,
        userAgent: req.headers['user-agent'],
        ipAddress: req.ip,
      }),
    {
      successMessage: '登录成功',
      errorMessage: '接单端验证码登录失败',
      scope: '[worker/auth/login/sms]',
    },
  ),
)

router.post(
  '/auth/devices/manage/list',
  createRateLimitMiddleware({
    scope: 'worker:devices-manage',
    windowMs: 60_000,
    max: 10,
    key: getBodyFieldRateLimitKey('username'),
  }),
  createRouteHandler((req) => manageWorkerSessions(req.body?.username, req.body?.password), {
    successMessage: 'ok',
    errorMessage: '读取登录设备失败',
    scope: '[worker/auth/devices/manage/list]',
  }),
)

router.post(
  '/auth/devices/manage/delete',
  createRateLimitMiddleware({
    scope: 'worker:devices-manage-delete',
    windowMs: 60_000,
    max: 10,
    key: getBodyFieldRateLimitKey('username'),
  }),
  createRouteHandler(
    (req) =>
      deleteWorkerSessionWithCredentials(
        req.body?.username,
        req.body?.password,
        req.body?.sessionId,
      ),
    {
      successMessage: '登录设备已删除',
      errorMessage: '删除登录设备失败',
      scope: '[worker/auth/devices/manage/delete]',
    },
  ),
)

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]',
  }),
)

export default router
