/**
 * 奖励记录控制器
 * @module controllers/promotion/rewardController
 */

const db = require('../../config/database');

/**
 * 获取奖励记录列表
 * @function getRewards
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.getRewards = async (req, res, next) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      user = '',
      reward_type = '',
      status = ''
    } = req.query;

    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    let whereConditions = [];
    let queryParams = [];

    if (user) {
      whereConditions.push('(user_name LIKE ? OR user_phone LIKE ?)');
      queryParams.push(`%${user}%`, `%${user}%`);
    }

    if (reward_type) {
      whereConditions.push('reward_type = ?');
      queryParams.push(reward_type);
    }

    if (status) {
      whereConditions.push('status = ?');
      queryParams.push(status);
    }

    const whereClause = whereConditions.length > 0 
      ? `WHERE ${whereConditions.join(' AND ')}` 
      : '';

    // 获取总数
    const countSql = `SELECT COUNT(*) as total FROM promotion_rewards ${whereClause}`;
    const countResult = await db.query(countSql, queryParams);
    const total = countResult[0].total;

    // 获取数据
    const dataSql = `
      SELECT 
        id, user_id, user_name, user_phone, activity_id, activity_name,
        reward_type, reward_amount, status, issued_at, created_at
      FROM promotion_rewards 
      ${whereClause}
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
    `;

    const dataParams = [...queryParams, limit, offset];
    const rewards = await db.query(dataSql, dataParams);

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: rewards,
      pagination: {
        current: parseInt(page),
        pageSize: limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 发放奖励
 * @function issueReward
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.issueReward = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 检查奖励记录是否存在
    const reward = await db.query(
      'SELECT * FROM promotion_rewards WHERE id = ?',
      [id]
    );

    if (reward.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '奖励记录不存在'
      });
    }

    const rewardData = reward[0];

    if (rewardData.status !== 'pending') {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '只有待发放状态的奖励可以发放'
      });
    }

    // 更新奖励状态为已发放
    await db.query(
      'UPDATE promotion_rewards SET status = "issued", issued_at = NOW() WHERE id = ?',
      [id]
    );

    // 根据奖励类型执行相应的发放逻辑
    try {
      switch (rewardData.reward_type) {
        case 'cash':
          // 现金奖励发放逻辑
          // 这里可以集成支付系统或记录到用户账户
          console.log(`发放现金奖励: ${rewardData.reward_amount}元给用户 ${rewardData.user_name}`);
          break;
        
        case 'points':
          // 积分奖励发放逻辑
          // 这里可以更新用户积分
          console.log(`发放积分奖励: ${rewardData.reward_amount}积分给用户 ${rewardData.user_name}`);
          break;
        
        case 'coupon':
          // 优惠券发放逻辑
          // 这里可以生成优惠券并关联到用户
          console.log(`发放优惠券奖励给用户 ${rewardData.user_name}`);
          break;
        
        default:
          console.log(`未知奖励类型: ${rewardData.reward_type}`);
      }
    } catch (distributionError) {
      // 如果发放失败，回滚奖励状态
      await db.query(
        'UPDATE promotion_rewards SET status = "failed" WHERE id = ?',
        [id]
      );
      
      console.error('奖励发放失败:', distributionError);
      
      return res.status(500).json({
        success: false,
        code: 500,
        message: '奖励发放失败'
      });
    }

    res.json({
      success: true,
      code: 200,
      message: '奖励发放成功'
    });
  } catch (error) {
    next(error);
  }
};