// lib/membership-activate.js
// 🔒 会员订单支付成功后激活权益（提取自 membership.js /buy，供支付回调调用）
// 设计：/buy 只创建 pending_pay 待支付订单；支付回调确认到账后调用本模块发放权益。
// 幂等：仅当订单状态为 pending_pay 时发放，回调后状态变为 pending_ship 不会重复发放。
const { get, run, transaction } = require('../utils/db');

// 仅处理会员类订单（remark 含 "会员:" / "购买会员:"）
function isMembershipOrder(order) {
  if (!order) return false;
  const remark = String(order.remark || '');
  return remark.includes('购买会员') || /会员[:：]/.test(remark);
}

// 从会员订单 remark 解析 plan_id（"购买会员:白银月卡" -> 需反查，直接在订单上找 plan）
// 实际方案：下单时把 plan_id 写入订单。兼容旧数据：通过 remark 查找 plan。
function activateMembership(orderId) {
  try {
    const order = get('SELECT * FROM orders WHERE id=?', [orderId]);
    if (!order || order.status !== 'pending_pay') {
      // 仅待支付订单在回调时激活；已付/其它状态不重复发放
      return { activated: false, reason: 'not_pending_pay' };
    }
    if (!isMembershipOrder(order)) {
      return { activated: false, reason: 'not_membership_order' };
    }

    // 解析 plan：优先用 remark 中的 plan{N} 标记，其次 order.plan_id，再次名称匹配
    let plan = null;
    const marker = String(order.remark || '').match(/plan(\d+)/);
    if (marker && marker[1]) {
      plan = get('SELECT * FROM membership_plans WHERE id=?', [Number(marker[1])]);
    }
    if (!plan && order.plan_id) {
      plan = get('SELECT * FROM membership_plans WHERE id=?', [order.plan_id]);
    }
    if (!plan) {
      // 兼容：从 remark "购买会员:名称" 匹配
      const m = String(order.remark).match(/购买会员[:：]\s*([^:]+)/);
      const name = m && m[1] ? m[1].trim() : '';
      if (name) plan = get("SELECT * FROM membership_plans WHERE name=? AND status=1", [name]);
    }
    if (!plan) return { activated: false, reason: 'plan_not_found' };

    transaction(() => {
      // 幂等：同用户同套餐已有 active 会员则不重复计费发放
      const existing = get("SELECT id FROM user_memberships WHERE user_id=? AND plan_id=? AND status='active'", [order.user_id, plan.id]);
      if (!existing) {
        const now = new Date();
        let endTime = new Date(now);
        if (plan.type === 'monthly') endTime.setMonth(endTime.getMonth() + 1);
        else if (plan.type === 'quarterly') endTime.setMonth(endTime.getMonth() + 3);
        else if (plan.type === 'yearly') endTime.setFullYear(endTime.getFullYear() + 1);
        else if (plan.type === 'permanent') endTime.setFullYear(endTime.getFullYear() + 50);
        run('INSERT INTO user_memberships(user_id,plan_id,start_time,end_time,status) VALUES(?,?,?,?,?)',
          [order.user_id, plan.id, now.toISOString(), endTime.toISOString(), 'active']);
      }
      // 加经验/升级
      if (plan.give_experience > 0) {
        const ex = plan.give_experience;
        run('UPDATE users SET experience=experience+?, level_id=CASE WHEN (experience+?)>=8000 THEN 4 WHEN (experience+?)>=2000 THEN 3 WHEN (experience+?)>=500 THEN 2 ELSE level_id END WHERE id=?',
          [ex, ex, ex, ex, order.user_id]);
      }
      // 送优惠券
      if (plan.give_coupon_ids) {
        const couponIds = String(plan.give_coupon_ids).split(',').map(Number).filter(Boolean);
        for (const cid of couponIds) {
          const coupon = get('SELECT * FROM coupons WHERE id=?', [cid]);
          if (coupon) {
            const gone = get('SELECT id FROM user_coupons WHERE user_id=? AND coupon_id=?', [order.user_id, cid]);
            if (!gone) {
              const expired = new Date();
              expired.setDate(expired.getDate() + (coupon.valid_days || 30));
              run('INSERT INTO user_coupons(user_id,coupon_id,expired_time) VALUES(?,?,?)', [order.user_id, cid, expired.toISOString()]);
            }
          }
        }
      }
      // 🩹联动：付费会员购买成功 → 自动开通分销（分销权限随会员权益发放）
      // 用户成为分销商，分销等级至少为普通分销商(1)；按会员等级映射更高档位(白银=1/黄金=2/钻石=3)
      const cur = get('SELECT distributor_status, distributor_level, level_id FROM users WHERE id=?', [order.user_id]);
      if (cur) {
        const levelMap = { 2: 1, 3: 2, 4: 3 };
        const mapped = levelMap[cur.level_id] || 1;
        const finalLevel = cur.distributor_status === 'active' ? Math.max(cur.distributor_level || 1, mapped) : mapped;
        run("UPDATE users SET distributor_status='active', distributor_level=? WHERE id=?", [finalLevel, order.user_id]);
      }
    });
    return { activated: true, plan_id: plan.id };
  } catch (e) {
    console.error('[会员激活] 失败:', e.message);
    return { activated: false, reason: 'error', error: e.message };
  }
}

module.exports = { activateMembership, isMembershipOrder };
