import { Router } from 'express'

import { createRateLimitMiddleware, getBodyFieldRateLimitKey } from '../../middleware/rate-limit.js'
import {
  getAdminSessionSummary,
  loginAdmin,
  logoutAdmin,
} from '../../services/admin/admin-auth-service.js'
import {
  resolveClientIp,
  resolveClientLocation,
  resolveUserAgent,
} from '../../services/admin/admin-login-log-service.js'
import { createJsonHandler, extractBearerToken } from './session.js'

const router = Router()

const adminLoginIpRateLimit = createRateLimitMiddleware({
  scope: 'admin:login:ip',
  windowMs: 60_000,
  max: 20,
})

const adminLoginAccountRateLimit = createRateLimitMiddleware({
  scope: 'admin:login:account',
  windowMs: 60_000,
  max: 10,
  key: getBodyFieldRateLimitKey('username'),
})

router.post(
  '/auth/login',
  adminLoginIpRateLimit,
  adminLoginAccountRateLimit,
  createJsonHandler(
    (req) =>
      loginAdmin(req.body?.username, req.body?.password, {
        ip: resolveClientIp(req),
        userAgent: resolveUserAgent(req),
        location: resolveClientLocation(req),
      }),
    {
      successMessage: '登录成功',
      errorMessage: '后台登录失败',
      scope: '[admin/auth/login]',
    },
  ),
)

router.get(
  '/auth/session',
  createJsonHandler((req) => getAdminSessionSummary(extractBearerToken(req)), {
    successMessage: 'ok',
    errorMessage: '读取后台登录态失败',
    scope: '[admin/auth/session]',
  }),
)

router.post(
  '/auth/logout',
  createJsonHandler((req) => logoutAdmin(extractBearerToken(req)), {
    successMessage: '已退出登录',
    errorMessage: '后台退出失败',
    scope: '[admin/auth/logout]',
  }),
)

export default router
