const express = require('express');
const router = express.Router();
const PaymentController = require('../controllers/payment');
const { authenticateToken, requireRole } = require('../middleware/auth');
const { body, param } = require('express-validator');

/**
 * @swagger
 * components:
 *   schemas:
 *     Payment:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 支付订单ID
 *         payment_no:
 *           type: string
 *           description: 支付订单号
 *         order_id:
 *           type: integer
 *           description: 关联订单ID
 *         user_id:
 *           type: integer
 *           description: 用户ID
 *         amount:
 *           type: number
 *           format: decimal
 *           description: 支付金额
 *         paid_amount:
 *           type: number
 *           format: decimal
 *           description: 实际支付金额
 *         payment_method:
 *           type: string
 *           enum: [wechat, alipay, balance]
 *           description: 支付方式
 *         status:
 *           type: string
 *           enum: [pending, paid, failed, refunded, cancelled]
 *           description: 支付状态
 *         transaction_id:
 *           type: string
 *           description: 第三方交易号
 *         paid_at:
 *           type: string
 *           format: date-time
 *           description: 支付时间
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updated_at:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 *     
 *     Refund:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 退款ID
 *         refund_no:
 *           type: string
 *           description: 退款订单号
 *         payment_id:
 *           type: integer
 *           description: 支付订单ID
 *         user_id:
 *           type: integer
 *           description: 用户ID
 *         refund_amount:
 *           type: number
 *           format: decimal
 *           description: 退款金额
 *         refund_reason:
 *           type: string
 *           description: 退款原因
 *         status:
 *           type: string
 *           enum: [pending, approved, rejected, completed]
 *           description: 退款状态
 *         processed_by:
 *           type: integer
 *           description: 处理人ID
 *         process_remark:
 *           type: string
 *           description: 处理备注
 *         processed_at:
 *           type: string
 *           format: date-time
 *           description: 处理时间
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *     
 *     PaymentStatistics:
 *       type: object
 *       properties:
 *         total_amount:
 *           type: number
 *           format: decimal
 *           description: 总支付金额
 *         total_count:
 *           type: integer
 *           description: 总支付笔数
 *         success_amount:
 *           type: number
 *           format: decimal
 *           description: 成功支付金额
 *         success_count:
 *           type: integer
 *           description: 成功支付笔数
 *         refund_amount:
 *           type: number
 *           format: decimal
 *           description: 退款金额
 *         refund_count:
 *           type: integer
 *           description: 退款笔数
 *         method_stats:
 *           type: array
 *           items:
 *             type: object
 *             properties:
 *               payment_method:
 *                 type: string
 *                 description: 支付方式
 *               amount:
 *                 type: number
 *                 format: decimal
 *                 description: 金额
 *               count:
 *                 type: integer
 *                 description: 笔数
 */

/**
 * @swagger
 * /api/v1/payments:
 *   post:
 *     summary: 创建支付订单
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - order_id
 *               - amount
 *               - payment_method
 *             properties:
 *               order_id:
 *                 type: integer
 *                 description: 订单ID
 *               amount:
 *                 type: number
 *                 format: decimal
 *                 description: 支付金额
 *               payment_method:
 *                 type: string
 *                 enum: [wechat, alipay, balance]
 *                 description: 支付方式
 *               return_url:
 *                 type: string
 *                 description: 支付成功回调地址
 *     responses:
 *       201:
 *         description: 支付订单创建成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Payment'
 *       400:
 *         description: 参数错误
 *       401:
 *         description: 未授权
 *       500:
 *         description: 服务器错误
 */
router.post('/', 
  authenticateToken,
  [
    body('order_id').isInt({ min: 1 }).withMessage('订单ID必须是正整数'),
    body('amount').isFloat({ min: 0.01 }).withMessage('支付金额必须大于0'),
    body('payment_method').isIn(['wechat', 'alipay', 'balance']).withMessage('支付方式无效')
  ],
  PaymentController.createPayment
);

/**
 * @swagger
 * /api/v1/payments/{paymentId}:
 *   get:
 *     summary: 获取支付订单详情
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: paymentId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 支付订单ID
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   $ref: '#/components/schemas/Payment'
 *       403:
 *         description: 无权访问
 *       404:
 *         description: 支付订单不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/:paymentId',
  authenticateToken,
  param('paymentId').isInt({ min: 1 }).withMessage('支付订单ID必须是正整数'),
  PaymentController.getPayment
);

/**
 * @swagger
 * /api/v1/payments/query/{paymentNo}:
 *   get:
 *     summary: 查询支付状态
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: paymentNo
 *         required: true
 *         schema:
 *           type: string
 *         description: 支付订单号
 *     responses:
 *       200:
 *         description: 查询成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     payment_no:
 *                       type: string
 *                       description: 支付订单号
 *                     status:
 *                       type: string
 *                       description: 支付状态
 *                     amount:
 *                       type: number
 *                       description: 支付金额
 *                     paid_at:
 *                       type: string
 *                       format: date-time
 *                       description: 支付时间
 *                     transaction_id:
 *                       type: string
 *                       description: 第三方交易号
 *       403:
 *         description: 无权访问
 *       404:
 *         description: 支付订单不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/query/:paymentNo',
  authenticateToken,
  PaymentController.queryPaymentStatus
);

/**
 * @swagger
 * /api/v1/payments/callback/wechat:
 *   post:
 *     summary: 微信支付回调
 *     tags: [支付管理]
 *     description: 微信支付异步通知接口
 *     requestBody:
 *       required: true
 *       content:
 *         application/xml:
 *           schema:
 *             type: string
 *     responses:
 *       200:
 *         description: 处理成功
 *         content:
 *           application/xml:
 *             schema:
 *               type: string
 */
router.post('/callback/wechat', PaymentController.handleWechatCallback);

/**
 * @swagger
 * /api/v1/payments/callback/alipay:
 *   post:
 *     summary: 支付宝支付回调
 *     tags: [支付管理]
 *     description: 支付宝异步通知接口
 *     requestBody:
 *       required: true
 *       content:
 *         application/x-www-form-urlencoded:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: 处理成功
 *         content:
 *           text/plain:
 *             schema:
 *               type: string
 */
router.post('/callback/alipay', PaymentController.handleAlipayCallback);

/**
 * @swagger
 * /api/v1/payments/{paymentId}/refund:
 *   post:
 *     summary: 申请退款
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: paymentId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 支付订单ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - refund_amount
 *               - refund_reason
 *             properties:
 *               refund_amount:
 *                 type: number
 *                 format: decimal
 *                 description: 退款金额
 *               refund_reason:
 *                 type: string
 *                 description: 退款原因
 *     responses:
 *       201:
 *         description: 退款申请提交成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Refund'
 *       400:
 *         description: 参数错误
 *       403:
 *         description: 无权操作
 *       500:
 *         description: 服务器错误
 */
router.post('/:paymentId/refund',
  authenticateToken,
  [
    param('paymentId').isInt({ min: 1 }).withMessage('支付订单ID必须是正整数'),
    body('refund_amount').isFloat({ min: 0.01 }).withMessage('退款金额必须大于0'),
    body('refund_reason').notEmpty().withMessage('退款原因不能为空')
  ],
  PaymentController.createRefund
);

/**
 * @swagger
 * /api/v1/payments/refunds/{refundId}:
 *   get:
 *     summary: 获取退款详情
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: refundId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 退款ID
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   $ref: '#/components/schemas/Refund'
 *       403:
 *         description: 无权访问
 *       404:
 *         description: 退款记录不存在
 *       500:
 *         description: 服务器错误
 */
router.get('/refunds/:refundId',
  authenticateToken,
  param('refundId').isInt({ min: 1 }).withMessage('退款ID必须是正整数'),
  PaymentController.getRefund
);

/**
 * @swagger
 * /api/v1/payments/refunds/{refundId}/process:
 *   put:
 *     summary: 处理退款（管理员）
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: refundId
 *         required: true
 *         schema:
 *           type: integer
 *         description: 退款ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [approved, rejected, completed]
 *                 description: 退款状态
 *               process_remark:
 *                 type: string
 *                 description: 处理备注
 *     responses:
 *       200:
 *         description: 处理成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   $ref: '#/components/schemas/Refund'
 *       400:
 *         description: 参数错误
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.put('/refunds/:refundId/process',
  authenticateToken,
  requireRole(['admin', 'super_admin']),
  [
    param('refundId').isInt({ min: 1 }).withMessage('退款ID必须是正整数'),
    body('status').isIn(['approved', 'rejected', 'completed']).withMessage('退款状态无效')
  ],
  PaymentController.processRefund
);

/**
 * @swagger
 * /api/v1/payments/statistics:
 *   get:
 *     summary: 获取支付统计信息（管理员）
 *     tags: [支付管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - 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: payment_method
 *         schema:
 *           type: string
 *           enum: [wechat, alipay, balance]
 *         description: 支付方式
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   $ref: '#/components/schemas/PaymentStatistics'
 *       403:
 *         description: 权限不足
 *       500:
 *         description: 服务器错误
 */
router.get('/statistics',
  authenticateToken,
  requireRole(['admin', 'super_admin']),
  PaymentController.getPaymentStatistics
);

module.exports = router;