const express = require('express');
const { body, query, param } = require('express-validator');
const UserManagementController = require('../../controllers/admin/userManagement');
const { requireRole } = require('../../middleware/auth');

const router = express.Router();

/**
 * @swagger
 * tags:
 *   name: Admin User Management
 *   description: 管理员用户管理相关接口
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     UserDetail:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 用户ID
 *         nickname:
 *           type: string
 *           description: 用户昵称
 *         phone:
 *           type: string
 *           description: 手机号
 *         email:
 *           type: string
 *           description: 邮箱
 *         user_type:
 *           type: string
 *           enum: [farmer, merchant]
 *           description: 用户类型
 *         status:
 *           type: string
 *           enum: [active, inactive, banned]
 *           description: 用户状态
 *         travel_count:
 *           type: integer
 *           description: 旅行次数
 *         animal_claim_count:
 *           type: integer
 *           description: 认领次数
 *         points:
 *           type: integer
 *           description: 积分
 *         level:
 *           type: string
 *           enum: [bronze, silver, gold, platinum]
 *           description: 用户等级
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         last_login_at:
 *           type: string
 *           format: date-time
 *           description: 最后登录时间
 *     UserStatistics:
 *       type: object
 *       properties:
 *         total_users:
 *           type: integer
 *           description: 用户总数
 *         active_users:
 *           type: integer
 *           description: 活跃用户数
 *         new_users_today:
 *           type: integer
 *           description: 今日新增用户
 *         new_users_week:
 *           type: integer
 *           description: 本周新增用户
 */

/**
 * @swagger
 * /admin/users:
 *   get:
 *     summary: 获取用户列表
 *     tags: [Admin User Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词（昵称、手机号、邮箱）
 *       - in: query
 *         name: userType
 *         schema:
 *           type: string
 *           enum: [farmer, merchant]
 *         description: 用户类型
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [active, inactive, banned]
 *         description: 用户状态
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *       - in: query
 *         name: sortField
 *         schema:
 *           type: string
 *           enum: [created_at, last_login_at, points, travel_count]
 *           default: created_at
 *         description: 排序字段
 *       - in: query
 *         name: sortOrder
 *         schema:
 *           type: string
 *           enum: [asc, desc]
 *           default: desc
 *         description: 排序方向
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     users:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/UserDetail'
 *                     pagination:
 *                       type: object
 *                       properties:
 *                         page:
 *                           type: integer
 *                         pageSize:
 *                           type: integer
 *                         total:
 *                           type: integer
 *                         totalPages:
 *                           type: integer
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/', 
  requireRole(['admin', 'super_admin']),
  [
    query('page').optional().isInt({ min: 1 }),
    query('pageSize').optional().isInt({ min: 1, max: 100 }),
    query('userType').optional().isIn(['farmer', 'merchant']),
    query('status').optional().isIn(['active', 'inactive', 'banned']),
    query('sortField').optional().isIn(['created_at', 'last_login_at', 'points', 'travel_count']),
    query('sortOrder').optional().isIn(['asc', 'desc'])
  ],
  UserManagementController.getUserList
);

/**
 * @swagger
 * /admin/users/{userId}:
 *   get:
 *     summary: 获取用户详情
 *     tags: [Admin User Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: userId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 用户ID
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     user:
 *                       allOf:
 *                         - $ref: '#/components/schemas/UserDetail'
 *                         - type: object
 *                           properties:
 *                             interests:
 *                               type: array
 *                               items:
 *                                 type: string
 *                               description: 用户兴趣
 *                             recentTravels:
 *                               type: array
 *                               items:
 *                                 type: object
 *                               description: 最近旅行记录
 *                             recentClaims:
 *                               type: array
 *                               items:
 *                                 type: object
 *                               description: 最近认领记录
 *       404:
 *         description: 用户不存在
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/:userId',
  requireRole(['admin', 'super_admin']),
  [
    param('userId').isInt({ min: 1 })
  ],
  UserManagementController.getUserDetail
);

/**
 * @swagger
 * /admin/users/{userId}/status:
 *   put:
 *     summary: 更新用户状态
 *     tags: [Admin User Management]
 *     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, banned]
 *                 description: 新状态
 *               reason:
 *                 type: string
 *                 description: 操作原因
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 无效的状态值
 *       404:
 *         description: 用户不存在
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.put('/:userId/status',
  requireRole(['admin', 'super_admin']),
  [
    param('userId').isInt({ min: 1 }),
    body('status').isIn(['active', 'inactive', 'banned']),
    body('reason').optional().isString()
  ],
  UserManagementController.updateUserStatus
);

/**
 * @swagger
 * /admin/users/batch-status:
 *   put:
 *     summary: 批量更新用户状态
 *     tags: [Admin User Management]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - userIds
 *               - status
 *             properties:
 *               userIds:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 description: 用户ID列表
 *               status:
 *                 type: string
 *                 enum: [active, inactive, banned]
 *                 description: 新状态
 *               reason:
 *                 type: string
 *                 description: 操作原因
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.put('/batch-status',
  requireRole(['admin', 'super_admin']),
  [
    body('userIds').isArray({ min: 1 }),
    body('userIds.*').isInt({ min: 1 }),
    body('status').isIn(['active', 'inactive', 'banned']),
    body('reason').optional().isString()
  ],
  UserManagementController.batchUpdateUserStatus
);

/**
 * @swagger
 * /admin/users/statistics:
 *   get:
 *     summary: 获取用户统计信息
 *     tags: [Admin User Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: period
 *         schema:
 *           type: string
 *           enum: [7d, 30d, 90d]
 *           default: 30d
 *         description: 统计周期
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     basicStats:
 *                       $ref: '#/components/schemas/UserStatistics'
 *                     levelDistribution:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           level:
 *                             type: string
 *                           count:
 *                             type: integer
 *                     trendData:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           date:
 *                             type: string
 *                             format: date
 *                           new_users:
 *                             type: integer
 *                           new_farmers:
 *                             type: integer
 *                           new_merchants:
 *                             type: integer
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/statistics',
  requireRole(['admin', 'super_admin']),
  [
    query('period').optional().isIn(['7d', '30d', '90d'])
  ],
  UserManagementController.getUserStatistics
);

/**
 * @swagger
 * /admin/users/export:
 *   get:
 *     summary: 导出用户数据
 *     tags: [Admin User Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: format
 *         schema:
 *           type: string
 *           enum: [csv, json]
 *           default: csv
 *         description: 导出格式
 *       - in: query
 *         name: userType
 *         schema:
 *           type: string
 *           enum: [farmer, merchant]
 *         description: 用户类型筛选
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [active, inactive, banned]
 *         description: 状态筛选
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 导出成功
 *         content:
 *           text/csv:
 *             schema:
 *               type: string
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     users:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/UserDetail'
 *                     total:
 *                       type: integer
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/export',
  requireRole(['admin', 'super_admin']),
  [
    query('format').optional().isIn(['csv', 'json']),
    query('userType').optional().isIn(['farmer', 'merchant']),
    query('status').optional().isIn(['active', 'inactive', 'banned'])
  ],
  UserManagementController.exportUsers
);

module.exports = router;