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

// 临时简单的支付控制器
const createPayment = async (req, res) => {
  try {
    const { order_id, amount, payment_method } = req.body;
    const userId = req.user?.id || 1;

    const payment = {
      id: Date.now(),
      payment_no: `PAY${Date.now()}`,
      order_id,
      user_id: userId,
      amount,
      payment_method,
      status: 'pending',
      created_at: new Date().toISOString()
    };

    res.status(201).json({
      success: true,
      message: '支付订单创建成功',
      data: payment
    });
  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建支付订单失败',
      error: error.message
    });
  }
};

const getPayment = async (req, res) => {
  try {
    const { paymentId } = req.params;
    
    const payment = {
      id: paymentId,
      payment_no: `PAY${paymentId}`,
      status: 'paid',
      amount: 100.00,
      created_at: new Date().toISOString()
    };

    res.json({
      success: true,
      data: payment
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取支付信息失败',
      error: error.message
    });
  }
};

// 路由定义
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('支付方式无效')
  ],
  createPayment
);

router.get('/:paymentId',
  authenticateToken,
  [param('paymentId').isInt({ min: 1 }).withMessage('支付订单ID必须是正整数')],
  getPayment
);

module.exports = router;