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

const router = express.Router();

/**
 * @swagger
 * tags:
 *   name: Admin Animal Management
 *   description: 管理员动物管理相关接口
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     AnimalDetail:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 动物ID
 *         name:
 *           type: string
 *           description: 动物名称
 *         species:
 *           type: string
 *           description: 动物物种
 *         breed:
 *           type: string
 *           description: 品种
 *         age:
 *           type: integer
 *           description: 年龄（月）
 *         gender:
 *           type: string
 *           enum: [male, female]
 *           description: 性别
 *         price:
 *           type: number
 *           description: 认领价格
 *         status:
 *           type: string
 *           enum: [available, claimed, unavailable]
 *           description: 状态
 *         description:
 *           type: string
 *           description: 动物描述
 *         images:
 *           type: array
 *           items:
 *             type: string
 *           description: 动物图片
 *         merchant_id:
 *           type: integer
 *           description: 商家ID
 *         merchant_name:
 *           type: string
 *           description: 商家名称
 *         claim_count:
 *           type: integer
 *           description: 被认领次数
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updated_at:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 *     AnimalStatistics:
 *       type: object
 *       properties:
 *         totalStats:
 *           type: object
 *           properties:
 *             total_animals:
 *               type: integer
 *               description: 动物总数
 *             available_animals:
 *               type: integer
 *               description: 可认领动物数
 *             claimed_animals:
 *               type: integer
 *               description: 已认领动物数
 *             total_claims:
 *               type: integer
 *               description: 总认领次数
 *             avg_price:
 *               type: number
 *               description: 平均价格
 *         speciesStats:
 *           type: array
 *           items:
 *             type: object
 *             properties:
 *               species:
 *                 type: string
 *               count:
 *                 type: integer
 *               avg_price:
 *                 type: number
 */

/**
 * @swagger
 * /admin/animals:
 *   get:
 *     summary: 获取动物列表
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: species
 *         schema:
 *           type: string
 *         description: 动物物种
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [available, claimed, unavailable]
 *         description: 动物状态
 *       - in: query
 *         name: merchant_id
 *         schema:
 *           type: integer
 *         description: 商家ID
 *       - in: query
 *         name: start_date
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: end_date
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *       - in: query
 *         name: sort_by
 *         schema:
 *           type: string
 *           enum: [created_at, updated_at, price, claim_count]
 *           default: created_at
 *         description: 排序字段
 *       - in: query
 *         name: sort_order
 *         schema:
 *           type: string
 *           enum: [asc, desc]
 *           default: desc
 *         description: 排序方向
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     animals:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/AnimalDetail'
 *                     pagination:
 *                       $ref: '#/components/schemas/Pagination'
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/',
  requireRole(['admin', 'super_admin']),
  [
    query('page').optional().isInt({ min: 1 }),
    query('limit').optional().isInt({ min: 1, max: 100 }),
    query('keyword').optional().isString(),
    query('species').optional().isString(),
    query('status').optional().isIn(['available', 'claimed', 'unavailable']),
    query('merchant_id').optional().isInt(),
    query('start_date').optional().isDate(),
    query('end_date').optional().isDate(),
    query('sort_by').optional().isIn(['created_at', 'updated_at', 'price', 'claim_count']),
    query('sort_order').optional().isIn(['asc', 'desc'])
  ],
  AnimalManagementController.getAnimalList
);

/**
 * @swagger
 * /admin/animals/{animal_id}:
 *   get:
 *     summary: 获取动物详情
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: animal_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 动物ID
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     animal:
 *                       $ref: '#/components/schemas/AnimalDetail'
 *                     claimStats:
 *                       type: object
 *                       properties:
 *                         total_claims:
 *                           type: integer
 *                         pending_claims:
 *                           type: integer
 *                         approved_claims:
 *                           type: integer
 *                         rejected_claims:
 *                           type: integer
 *                     recentClaims:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/AnimalClaim'
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 动物不存在
 */
router.get('/:animal_id',
  requireRole(['admin', 'super_admin']),
  [
    param('animal_id').isInt({ min: 1 })
  ],
  AnimalManagementController.getAnimalDetail
);

/**
 * @swagger
 * /admin/animals/{animal_id}/status:
 *   put:
 *     summary: 更新动物状态
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: animal_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 动物ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [available, claimed, unavailable]
 *                 description: 新状态
 *               reason:
 *                 type: string
 *                 description: 状态变更原因
 *     responses:
 *       200:
 *         description: 更新成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *       400:
 *         description: 参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 *       404:
 *         description: 动物不存在
 */
router.put('/:animal_id/status',
  requireRole(['admin', 'super_admin']),
  [
    param('animal_id').isInt({ min: 1 }),
    body('status').isIn(['available', 'claimed', 'unavailable']),
    body('reason').optional().isString().isLength({ max: 500 })
  ],
  AnimalManagementController.updateAnimalStatus
);

/**
 * @swagger
 * /admin/animals/batch/status:
 *   put:
 *     summary: 批量更新动物状态
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - animal_ids
 *               - status
 *             properties:
 *               animal_ids:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 description: 动物ID列表
 *               status:
 *                 type: string
 *                 enum: [available, claimed, unavailable]
 *                 description: 新状态
 *               reason:
 *                 type: string
 *                 description: 状态变更原因
 *     responses:
 *       200:
 *         description: 批量更新成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     updated_count:
 *                       type: integer
 *                       description: 更新的动物数量
 *       400:
 *         description: 参数错误
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.put('/batch/status',
  requireRole(['admin', 'super_admin']),
  [
    body('animal_ids').isArray({ min: 1 }),
    body('animal_ids.*').isInt({ min: 1 }),
    body('status').isIn(['available', 'claimed', 'unavailable']),
    body('reason').optional().isString().isLength({ max: 500 })
  ],
  AnimalManagementController.batchUpdateAnimalStatus
);

/**
 * @swagger
 * /admin/animals/statistics:
 *   get:
 *     summary: 获取动物统计信息
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/AnimalStatistics'
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/statistics',
  requireRole(['admin', 'super_admin']),
  AnimalManagementController.getAnimalStatistics
);

/**
 * @swagger
 * /admin/animals/export:
 *   get:
 *     summary: 导出动物数据
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: format
 *         schema:
 *           type: string
 *           enum: [csv, json]
 *           default: csv
 *         description: 导出格式
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: species
 *         schema:
 *           type: string
 *         description: 动物物种
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [available, claimed, unavailable]
 *         description: 动物状态
 *       - in: query
 *         name: merchant_id
 *         schema:
 *           type: integer
 *         description: 商家ID
 *       - in: query
 *         name: start_date
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始日期
 *       - in: query
 *         name: end_date
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 导出成功
 *         content:
 *           text/csv:
 *             schema:
 *               type: string
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     animals:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/AnimalDetail'
 *                     export_time:
 *                       type: string
 *                       format: date-time
 *                     total_count:
 *                       type: integer
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/export',
  requireRole(['admin', 'super_admin']),
  [
    query('format').optional().isIn(['csv', 'json']),
    query('keyword').optional().isString(),
    query('species').optional().isString(),
    query('status').optional().isIn(['available', 'claimed', 'unavailable']),
    query('merchant_id').optional().isInt(),
    query('start_date').optional().isDate(),
    query('end_date').optional().isDate()
  ],
  AnimalManagementController.exportAnimalData
);

/**
 * @swagger
 * /admin/animals/{animal_id}/claims:
 *   get:
 *     summary: 获取动物认领记录
 *     tags: [Admin Animal Management]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: animal_id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 动物ID
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [pending, approved, rejected, cancelled]
 *         description: 认领状态
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     claims:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/AnimalClaim'
 *                     pagination:
 *                       $ref: '#/components/schemas/Pagination'
 *       401:
 *         description: 未授权
 *       403:
 *         description: 权限不足
 */
router.get('/:animal_id/claims',
  requireRole(['admin', 'super_admin']),
  [
    param('animal_id').isInt({ min: 1 }),
    query('page').optional().isInt({ min: 1 }),
    query('limit').optional().isInt({ min: 1, max: 100 }),
    query('status').optional().isIn(['pending', 'approved', 'rejected', 'cancelled'])
  ],
  AnimalManagementController.getAnimalClaimRecords
);

module.exports = router;