import { Router } from 'express'

import {
  createManagedAdminUser,
  getAdminUserList,
  resetManagedAdminUserPassword,
  updateManagedAdminUserRole,
  updateManagedAdminUserStatus,
} from '../../services/admin/admin-auth-service.js'
import { createJsonHandler, getRequiredAdminSession, requireAdminRoles } from './session.js'

type AdminUserMutationResult = {
  user: {
    userId: number
    username: string
    role: string
    status?: string
  }
}

const router = Router()

router.use('/users', requireAdminRoles(['admin']))

router.get(
  '/users',
  createJsonHandler((req) => getAdminUserList(req.query), {
    successMessage: 'ok',
    errorMessage: '读取后台用户列表失败',
    scope: '[admin/users]',
  }),
)

router.post(
  '/users',
  createJsonHandler((req) => createManagedAdminUser(req.body), {
    successMessage: '后台用户已创建',
    errorMessage: '创建后台用户失败',
    scope: '[admin/users:create]',
    audit: (_req, data) => {
      const result = data as AdminUserMutationResult
      return {
        action: 'admin_user_created',
        targetType: 'admin_user',
        targetId: String(result.user.userId),
        data: {
          username: result.user.username,
          role: result.user.role,
          status: result.user.status,
        },
      }
    },
  }),
)

router.post(
  '/users/:userId/role',
  createJsonHandler(
    (req) =>
      updateManagedAdminUserRole(
        String(req.params.userId || ''),
        req.body,
        getRequiredAdminSession(req),
      ),
    {
      successMessage: '用户角色已更新',
      errorMessage: '更新用户角色失败',
      scope: '[admin/users/:userId/role]',
      audit: (_req, data) => {
        const result = data as AdminUserMutationResult
        return {
          action: 'admin_user_role_updated',
          targetType: 'admin_user',
          targetId: String(result.user.userId),
          data: {
            username: result.user.username,
            role: result.user.role,
          },
        }
      },
    },
  ),
)

router.post(
  '/users/:userId/status',
  createJsonHandler(
    (req) =>
      updateManagedAdminUserStatus(
        String(req.params.userId || ''),
        req.body,
        getRequiredAdminSession(req),
      ),
    {
      successMessage: '用户状态已更新',
      errorMessage: '更新用户状态失败',
      scope: '[admin/users/:userId/status]',
      audit: (_req, data) => {
        const result = data as AdminUserMutationResult
        return {
          action: 'admin_user_status_updated',
          targetType: 'admin_user',
          targetId: String(result.user.userId),
          data: {
            username: result.user.username,
            status: result.user.status,
          },
        }
      },
    },
  ),
)

router.post(
  '/users/:userId/reset-password',
  createJsonHandler(
    (req) => resetManagedAdminUserPassword(String(req.params.userId || ''), req.body),
    {
      successMessage: '用户密码已重置',
      errorMessage: '重置用户密码失败',
      scope: '[admin/users/:userId/reset-password]',
      audit: (_req, data) => {
        const result = data as AdminUserMutationResult
        return {
          action: 'admin_user_password_reset',
          targetType: 'admin_user',
          targetId: String(result.user.userId),
          data: {
            username: result.user.username,
          },
        }
      },
    },
  ),
)

export default router
