// ─────────────────────────────────────────────────────────────────────────────
//  downlineHelper.js
//  Jab bhi koi naya member approve ho, uske poore upline chain ka
//  total_downline increment karta hai.
//
//  Chain walk:
//    new member ka sponsor → uska sponsor → uska sponsor → ... → top tak
//    Har node ka total_downline + 1 hota hai
// ─────────────────────────────────────────────────────────────────────────────

import db from '../config/database.js';

/**
 * Walk the full upline chain starting from `sponsorMemberId`
 * and increment total_downline by 1 for every ancestor.
 *
 * @param {string} sponsorMemberId  – member_id (e.g. "RV001") of the direct sponsor
 */
export const incrementDownlineForAllUplines = async (sponsorMemberId) => {
  try {
    const visited   = new Set();
    let currentCode = sponsorMemberId;

    while (currentCode && !visited.has(currentCode)) {
      visited.add(currentCode);

      // Fetch current upline node
      const [rows] = await db.query(
        `SELECT id, member_id, sponsor_id
           FROM members
          WHERE member_id = ?`,
        [currentCode]
      );

      if (!rows.length) {
        console.warn(`⚠️ [DOWNLINE] Member not found in chain: ${currentCode}`);
        break;
      }

      const upline = rows[0];

      // Increment total_downline
      await db.query(
        `UPDATE members
            SET total_downline = total_downline + 1,
                updated_at     = NOW()
          WHERE id = ?`,
        [upline.id]
      );

      console.log(`📊 [DOWNLINE] ${upline.member_id} → total_downline +1`);

      // Move up the chain
      currentCode = upline.sponsor_id;
    }

    console.log(`✅ [DOWNLINE] Chain update complete from sponsor: ${sponsorMemberId}`);

  } catch (err) {
    // Never block the main approval flow
    console.error(`❌ [DOWNLINE] incrementDownlineForAllUplines error:`, err.message);
  }
};