import { Router } from 'express'

import { createRateLimitMiddleware, getBodyFieldRateLimitKey } from '../../middleware/rate-limit.js'
import { getAdminSessionSummary, loginAdmin } 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()

router.post('/auth/login', createRateLimitMiddleware({
  scope: 'admin:login',
  windowMs: 60_000,
  max: 10,
  key: getBodyFieldRateLimitKey('username'),
}), 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(
  () => ({ success: true }),
  {
    successMessage: '已退出登录',
    errorMessage: '后台退出失败',
    scope: '[admin/auth/logout]',
  },
))

export default router
