/**
 * 满减满送活动规则引擎
 * 
 * 核心逻辑：计算订单最优满减方案
 * 支持：满减/送券/送积分/满件打折/阶梯满减
 */
const { get, all } = require('../utils/db');

/**
 * 计算可用满减活动
 * @param {number} totalAmount - 订单商品总额
 * @param {number} totalQuantity - 订单商品总件数
 * @param {number[]} productIds - 商品ID列表
 * @param {number[]} categoryIds - 分类ID列表
 * @returns {{applicable:Array, best:Object|null, benefitAmount:number, benefitDesc:string}}
 */
    // NOTE: calcBestPromotion 逻辑清晰、业务稳定，当前无需重构

function calcBestPromotion(totalAmount, totalQuantity, productIds = [], categoryIds = []) {
  const now = new Date().toISOString().replace('T', ' ').substring(0, 19);
  
  // 1. 获取所有生效活动
  const promotions = all(`SELECT * FROM promotions WHERE status=1 
    AND (is_forever=1 OR (start_time<=? AND end_time>=?)) 
    ORDER BY sort ASC, id ASC`, [now, now]);

  if (!promotions.length) return { applicable: [], best: null, benefitAmount: 0, benefitDesc: '' };

  const applicable = [];
  let best = null;
  let bestAmount = 0;

  for (const promo of promotions) {
    // 2. 检查商品范围
    if (!checkScope(promo, productIds, categoryIds)) continue;

    // 3. 解析规则
    const rules = JSON.parse(promo.rules || '[]');
    if (!rules.length) continue;

    // 4. 匹配规则
    for (let i = rules.length - 1; i >= 0; i--) {
      const rule = rules[i];
      let matched = false;

      if (rule.cond_type === 'amount' && totalAmount >= rule.cond_val) {
        matched = true;
      } else if (rule.cond_type === 'quantity' && totalQuantity >= rule.cond_val) {
        matched = true;
      }

      if (matched) {
        let benefitAmount = 0;
        let benefitDesc = '';

        if (promo.type === 'full_reduce' || promo.type === 'step_reduce') {
          benefitAmount = rule.benefit_val;
          benefitDesc = `满¥${rule.cond_val}减¥${rule.benefit_val}`;
        } else if (promo.type === 'full_gift_coupon') {
          benefitAmount = 0;
          benefitDesc = `满¥${rule.cond_val}送优惠券`;
        } else if (promo.type === 'full_gift_points') {
          benefitAmount = 0;
          benefitDesc = `满¥${rule.cond_val}送${rule.benefit_val}积分`;
        } else if (promo.type === 'full_discount') {
          benefitAmount = Math.round(totalAmount * (1 - rule.benefit_val) * 100) / 100;
          benefitDesc = `满${rule.cond_val}件打${(rule.benefit_val * 10).toFixed(1)}折`;
        }

        const matchedRule = {
          promotionId: promo.id,
          promotionName: promo.name,
          ruleIndex: i,
          rule,
          benefitAmount,
          benefitDesc,
          condDesc: `满¥${rule.cond_val}`,
        };
        applicable.push(matchedRule);

        if (benefitAmount > bestAmount) {
          bestAmount = benefitAmount;
          best = matchedRule;
        }

        // 阶梯满减取最优档位后跳出
        if (promo.type === 'step_reduce' || promo.type === 'full_reduce') break;
      }
    }
  }

  return { applicable, best, benefitAmount: bestAmount, benefitDesc: best ? best.benefitDesc : '' };
}

/**
 * 检查商品范围
 */
function checkScope(promo, productIds, categoryIds) {
  const scopeType = promo.scope_type || 'all';
  const scopeValues = JSON.parse(promo.scope_values || '[]');
  
  if (scopeType === 'all') return true;
  if (scopeType === 'category') {
    return categoryIds.some(cid => scopeValues.includes(cid));
  }
  if (scopeType === 'product') {
    return productIds.some(pid => scopeValues.includes(pid));
  }
  if (scopeType === 'exclude') {
    return !productIds.some(pid => scopeValues.includes(pid));
  }
  return true;
}

module.exports = { calcBestPromotion };
