import { Router } from 'express';
import { body, param } from 'express-validator';
import { UserService } from '../services/UserService.js';
import { authenticate, authorize } from '../middleware/auth.js';
import { asyncHandler } from '../middleware/error.js';
import { validateRequest } from '../middleware/validate.js';

const router = Router();
const userService = new UserService();

// 所有路由需要管理员权限
router.use(authenticate, authorize('admin'));

// 获取用户列表
router.get(
  '/',
  asyncHandler(async (req, res) => {
    const { page = 1, pageSize = 20, keyword, role, status } = req.query;
    
    const result = await userService.getUsers({
      page: Number(page),
      pageSize: Number(pageSize),
      keyword: keyword as string,
      role: role as string,
      status: status as string,
    });
    
    res.json({
      success: true,
      data: result,
    });
  })
);

// 获取单个用户
router.get(
  '/:id',
  [
    param('id').isInt().withMessage('用户ID无效'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const user = await userService.getUserById(Number(req.params.id));
    
    res.json({
      success: true,
      data: user,
    });
  })
);

// 创建用户
router.post(
  '/',
  [
    body('username')
      .notEmpty().withMessage('用户名不能为空')
      .isLength({ min: 3, max: 50 }).withMessage('用户名长度为3-50个字符'),
    body('password')
      .notEmpty().withMessage('密码不能为空')
      .isLength({ min: 6 }).withMessage('密码长度至少6个字符'),
    body('email').optional().isEmail().withMessage('邮箱格式不正确'),
    body('role').optional().isIn(['admin', 'editor', 'operator']).withMessage('角色无效'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const user = await userService.createUser(req.body);
    
    res.status(201).json({
      success: true,
      data: user,
    });
  })
);

// 更新用户
router.put(
  '/:id',
  [
    param('id').isInt().withMessage('用户ID无效'),
    body('email').optional().isEmail().withMessage('邮箱格式不正确'),
    body('role').optional().isIn(['admin', 'editor', 'operator']).withMessage('角色无效'),
    body('status').optional().isIn(['active', 'disabled', 'pending']).withMessage('状态无效'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const user = await userService.updateUser(Number(req.params.id), req.body);
    
    res.json({
      success: true,
      data: user,
    });
  })
);

// 删除用户
router.delete(
  '/:id',
  [
    param('id').isInt().withMessage('用户ID无效'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    await userService.deleteUser(Number(req.params.id), req.user!.userId);
    
    res.json({
      success: true,
      message: '用户已删除',
    });
  })
);

export default router;
