const express = require('express');
const { body } = require('express-validator');
const { authMiddleware, adminMiddleware, managerMiddleware } = require('../middleware/auth');
const router = express.Router();
const userController = require('../controllers/userController');

/**
 * @swagger
 * tags:
 *   name: Users
 *   description: 用户管理
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       required:
 *         - username
 *         - email
 *         - password
 *         - real_name
 *         - id_card
 *       properties:
 *         id:
 *           type: integer
 *           description: 用户ID
 *         username:
 *           type: string
 *           description: 用户名
 *         email:
 *           type: string
 *           format: email
 *           description: 邮箱地址
 *         real_name:
 *           type: string
 *           description: 真实姓名
 *         id_card:
 *           type: string
 *           description: 身份证号
 *         phone:
 *           type: string
 *           description: 手机号
 *         status:
 *           type: string
 *           enum: [active, inactive, suspended, locked]
 *           description: 用户状态
 */

/**
 * @swagger
 * /api/users/register:
 *   post:
 *     summary: 用户注册
 *     tags: [Users]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - email
 *               - password
 *               - real_name
 *               - id_card
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               email:
 *                 type: string
 *                 format: email
 *                 description: 邮箱地址
 *               password:
 *                 type: string
 *                 description: 密码
 *               real_name:
 *                 type: string
 *                 description: 真实姓名
 *               id_card:
 *                 type: string
 *                 description: 身份证号
 *               phone:
 *                 type: string
 *                 description: 手机号
 *     responses:
 *       201:
 *         description: 注册成功
 *       400:
 *         description: 输入数据验证失败
 *       500:
 *         description: 服务器内部错误
 */
router.post('/register', 
  [
    body('username').notEmpty().isLength({ min: 3, max: 50 }),
    body('email').isEmail(),
    body('password').isLength({ min: 6 }),
    body('real_name').notEmpty(),
    body('id_card').matches(/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/),
    body('phone').optional().matches(/^1[3-9]\d{9}$/)
  ],
  userController.register
);

/**
 * @swagger
 * /api/users/login:
 *   post:
 *     summary: 用户登录
 *     tags: [Users]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 description: 用户名
 *               password:
 *                 type: string
 *                 description: 密码
 *     responses:
 *       200:
 *         description: 登录成功
 *       401:
 *         description: 用户名或密码错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/login', userController.login);

/**
 * @swagger
 * /api/users/profile:
 *   get:
 *     summary: 获取用户信息
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       401:
 *         description: 未授权
 *       404:
 *         description: 用户不存在
 */
router.get('/profile', authMiddleware, userController.getProfile);

/**
 * @swagger
 * /api/users/profile:
 *   put:
 *     summary: 更新用户信息
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phone:
 *                 type: string
 *                 description: 手机号
 *               real_name:
 *                 type: string
 *                 description: 真实姓名
 *               avatar:
 *                 type: string
 *                 description: 头像URL
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 输入数据验证失败
 *       401:
 *         description: 未授权
 */
router.put('/profile', 
  authMiddleware,
  [
    body('phone').optional().matches(/^1[3-9]\d{9}$/),
    body('real_name').optional().notEmpty()
  ],
  userController.updateProfile
);

/**
 * @swagger
 * /api/users/change-password:
 *   put:
 *     summary: 修改密码
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - old_password
 *               - new_password
 *             properties:
 *               old_password:
 *                 type: string
 *                 description: 原密码
 *               new_password:
 *                 type: string
 *                 description: 新密码
 *     responses:
 *       200:
 *         description: 修改成功
 *       400:
 *         description: 原密码错误
 *       401:
 *         description: 未授权
 */
router.put('/change-password',
  authMiddleware,
  [
    body('old_password').notEmpty(),
    body('new_password').isLength({ min: 6 })
  ],
  userController.changePassword
);

/**
 * @swagger
 * /api/users:
 *   get:
 *     summary: 获取用户列表（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *     responses:
 *       200:
 *         description: 获取成功
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/', 
  authMiddleware, 
  adminMiddleware, 
  userController.getUsers
);

/**
 * @swagger
 * /api/users/{userId}/status:
 *   put:
 *     summary: 更新用户状态（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [active, inactive, suspended, locked]
 *                 description: 用户状态
 *     responses:
 *       200:
 *         description: 更新成功
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 用户不存在
 */
router.put('/:userId/status',
  authMiddleware,
  adminMiddleware,
  [
    body('status').isIn(['active', 'inactive', 'suspended', 'locked'])
  ],
  userController.updateUserStatus
);

/**
 * @swagger
 * /api/users/{userId}/accounts:
 *   get:
 *     summary: 获取用户账户列表
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     responses:
 *       200:
 *         description: 获取成功
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/:userId/accounts',
  authMiddleware,
  userController.getUserAccounts
);

// 新增的管理员路由
/**
 * @swagger
 * /api/users:
 *   post:
 *     summary: 创建用户（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - email
 *               - password
 *               - real_name
 *               - id_card
 *             properties:
 *               username:
 *                 type: string
 *               email:
 *                 type: string
 *               password:
 *                 type: string
 *               real_name:
 *                 type: string
 *               id_card:
 *                 type: string
 *               phone:
 *                 type: string
 *               role_id:
 *                 type: integer
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.post('/', 
  authMiddleware,
  adminMiddleware,
  [
    body('username').notEmpty().isLength({ min: 3, max: 50 }),
    body('email').isEmail(),
    body('password').isLength({ min: 6 }),
    body('real_name').notEmpty(),
    body('id_card').matches(/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/),
    body('phone').optional().matches(/^1[3-9]\d{9}$/)
  ],
  userController.createUser
);

/**
 * @swagger
 * /api/users/{userId}:
 *   get:
 *     summary: 获取用户详情
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 获取成功
 *       401:
 *         description: 未授权
 *       404:
 *         description: 用户不存在
 */
router.get('/:userId',
  authMiddleware,
  userController.getUserById
);

/**
 * @swagger
 * /api/users/{userId}:
 *   put:
 *     summary: 更新用户信息（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *               email:
 *                 type: string
 *               real_name:
 *                 type: string
 *               id_card:
 *                 type: string
 *               phone:
 *                 type: string
 *               role_id:
 *                 type: integer
 *               status:
 *                 type: string
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 用户不存在
 */
router.put('/:userId',
  authMiddleware,
  adminMiddleware,
  [
    body('username').optional().isLength({ min: 3, max: 50 }),
    body('email').optional().isEmail(),
    body('real_name').optional().notEmpty(),
    body('id_card').optional().matches(/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/),
    body('phone').optional().matches(/^1[3-9]\d{9}$/)
  ],
  userController.updateUser
);

/**
 * @swagger
 * /api/users/{userId}:
 *   delete:
 *     summary: 删除用户（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 删除成功
 *       400:
 *         description: 不能删除自己的账户
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 用户不存在
 */
router.delete('/:userId',
  authMiddleware,
  adminMiddleware,
  userController.deleteUser
);

/**
 * @swagger
 * /api/users/{userId}/reset-password:
 *   post:
 *     summary: 重置用户密码（管理员）
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - newPassword
 *             properties:
 *               newPassword:
 *                 type: string
 *     responses:
 *       200:
 *         description: 重置成功
 *       400:
 *         description: 请求参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 用户不存在
 */
router.post('/:userId/reset-password',
  authMiddleware,
  adminMiddleware,
  [
    body('newPassword').isLength({ min: 6 })
  ],
  userController.resetPassword
);

module.exports = router;