// ─────────────────────────────────────────────────────────────────────────────
//  StarClubHelper.js  (v4 — Final Correct Version)
//
//  Entry:     5 direct referrals → L0 join karo
//  Promotion: Mere is level par aane ke BAAD jab 5 aur log is level par aayein
//             → main next level par promote ho jaata hoon
//
//  DB column needed:
//    ALTER TABLE members
//    ADD COLUMN star_club_level_entry_count INT NOT NULL DEFAULT 0;
// ─────────────────────────────────────────────────────────────────────────────

import db from '../config/database.js';
import { distributeUpgradeIncome } from './Levelincomehelper.js';

const STAR_CLUB_LEVELS = [
  { level: 0, title: 'Star Club Entry', plan_upgrade: 0,      star_income: 0       },
  { level: 1, title: 'Star Club 1',     plan_upgrade: 0,      star_income: 1000    },
  { level: 2, title: 'Star Club 2',     plan_upgrade: 3000,   star_income: 500     },
  { level: 3, title: 'Star Club 3',     plan_upgrade: 6000,   star_income: 4000    },
  { level: 4, title: 'Star Club 4',     plan_upgrade: 12000,  star_income: 13000   },
  { level: 5, title: 'Star Club 5',     plan_upgrade: 24000,  star_income: 51000   },
  { level: 6, title: 'Star Club 6',     plan_upgrade: 48000,  star_income: 102000  },
  { level: 7, title: 'Star Club 7',     plan_upgrade: 96000,  star_income: 404000  },
];

export const MAX_STAR_CLUB_LEVEL = 7;
export const PROMOTE_AFTER_COUNT = 5;
export { STAR_CLUB_LEVELS };

// ─────────────────────────────────────────────────────────────────────────────
//  Internal: Member promote karo → income + plan upgrade + counter reset
// ─────────────────────────────────────────────────────────────────────────────
const promoteMember = async (member) => {
  const oldLevel = member.star_club_level;
  const newLevel = oldLevel + 1;
  const config   = STAR_CLUB_LEVELS[newLevel];
  const curPlan  = parseFloat(member.plan) || 0;

  let incomeToAdd    = config.star_income;
  let newPlan        = curPlan;
  let planUpgraded   = false;
  let planAlreadyHad = false;

  if (config.plan_upgrade > 0) {
    if (curPlan >= config.plan_upgrade) {
      incomeToAdd   += config.plan_upgrade;
      planAlreadyHad = true;
    } else {
      newPlan      = config.plan_upgrade;
      planUpgraded = true;
    }
  }

  // Level up + counter 0 reset (naye level par fresh start)
  await db.query(
    `UPDATE members
        SET star_club_level             = ?,
            plan                        = ?,
            star_club_level_entry_count = 0,
            star_club_income            = star_club_income + ?,
            wallet_balance              = wallet_balance   + ?,
            total_income                = total_income     + ?,
            updated_at                  = NOW()
      WHERE id = ?`,
    [newLevel, newPlan, incomeToAdd, incomeToAdd, incomeToAdd, member.id]
  );

  let desc = `${config.title} | SC Income ₹${config.star_income.toLocaleString('en-IN')}`;
  if (planUpgraded)   desc += ` | Plan upgraded to ₹${config.plan_upgrade.toLocaleString('en-IN')}`;
  if (planAlreadyHad) desc += ` + Plan benefit ₹${config.plan_upgrade.toLocaleString('en-IN')} (already purchased)`;

  await db.query(
    `INSERT INTO transactions
       (user_type, user_id, user_member_id, transaction_type, amount, description, created_at)
     VALUES ('member', ?, ?, 'STAR_CLUB_INCOME', ?, ?, NOW())`,
    [member.id, member.member_id, incomeToAdd, desc]
  );

  console.log(
    `⭐ [STAR_CLUB] ${member.member_id} | SC${oldLevel}→SC${newLevel} | ` +
    `Income: ₹${incomeToAdd.toLocaleString('en-IN')}` +
    (planUpgraded   ? ` | Plan→₹${newPlan.toLocaleString('en-IN')}` : '') +
    (planAlreadyHad ? ` | Plan already had, credited as income` : '')
  );

  if (planUpgraded && config.plan_upgrade > 0) {
    distributeUpgradeIncome(member.id, curPlan, config.plan_upgrade).catch((err) => {
      console.error(`❌ [STAR_CLUB→LEVEL_INCOME] failed for ${member.member_id}:`, err.message);
    });
  }

  // ── Promote hone ke baad: naye level par already kitne log hain? ──────────
  // Agar naye level (e.g. L1) par already X log pehle se hain,
  // toh is newly promoted member ka counter = X se shuru hoga
  // (kyunki wo log pehle aa chuke hain — unhe count karna zaroori hai)
  const [{ cnt }] = (await db.query(
    `SELECT COUNT(*) AS cnt
       FROM members
      WHERE star_club_level = ?
        AND id != ?`,
    [newLevel, member.id]
  ))[0];

  // Agar naye level par koi nahi tha → counter 0 hi rehta hai (already set above)
  // Agar the → unka count set karo taaki future promotions sahi calculate hon
  // NOTE: Yeh count "mere aane se pehle kitne the" hai — ye already existing members
  // is member ke liye nahi count karenge, sirf FUTURE entries count karengi.
  // Counter 0 hi sahi hai — future mein jo L(newLevel) join karenge woh count honge.
  console.log(
    `ℹ️ [STAR_CLUB] ${member.member_id} ab L${newLevel} par hai | ` +
    `L${newLevel} par pehle se ${cnt} members hain | Counter 0 se shuru`
  );
};

// ─────────────────────────────────────────────────────────────────────────────
//  Internal: Ek level ke saare members ka counter +1 karo
//  Phir jo counter >= 5 ho gaye unhe promote karo (cascading)
//
//  @param level        — konsa level join hua (naye member ne)
//  @param excludeId    — naya member (uska counter nahi badhana)
// ─────────────────────────────────────────────────────────────────────────────
const incrementAndCheckLevel = async (level, excludeId) => {
  if (level >= MAX_STAR_CLUB_LEVEL) return;

  // Is level ke saare existing members fetch karo
  const [members] = await db.query(
    `SELECT id, member_id, star_club_level, star_club_level_entry_count, plan
       FROM members
      WHERE star_club_level = ?
        AND id != ?`,
    [level, excludeId]
  );

  for (const member of members) {
    const newCount = member.star_club_level_entry_count + 1;

    await db.query(
      `UPDATE members
          SET star_club_level_entry_count = ?,
              updated_at                  = NOW()
        WHERE id = ?`,
      [newCount, member.id]
    );

    console.log(
      `📊 [STAR_CLUB] ${member.member_id} L${level} counter: ` +
      `${member.star_club_level_entry_count} → ${newCount}`
    );

    // Counter 5 hua → promote!
    if (newCount >= PROMOTE_AFTER_COUNT) {
      const [fresh] = await db.query(
        `SELECT id, member_id, star_club_level, plan FROM members WHERE id = ?`,
        [member.id]
      );

      if (fresh.length && fresh[0].star_club_level < MAX_STAR_CLUB_LEVEL) {
        await promoteMember(fresh[0]);

        // ── CASCADE ────────────────────────────────────────────────────────
        // Yeh member ab L(level+1) par aa gaya.
        // Ab L(level+1) par jo pehle se log hain unka counter +1 hoga?
        // NAHI — kyunki yeh member khud promote hua hai, koi naya "joiner" nahi hai.
        // Sirf jab koi NAYA member L(n) join kare tab counter badhta hai.
        // Isliye cascade yahan NAHI hoga — sahi behavior hai.
      }
    }
  }
};

// ─────────────────────────────────────────────────────────────────────────────
//  Main Export: Jab kisi member ke 5 direct ho jaayein
// ─────────────────────────────────────────────────────────────────────────────
export const processStarClubOnNewEntry = async (newMemberUUID, newMemberCode) => {
  try {
    // Step 1: New member → L0, counter = 0
    await db.query(
      `UPDATE members
          SET star_club_level             = 0,
              star_club_level_entry_count = 0,
              updated_at                  = NOW()
        WHERE id = ?`,
      [newMemberUUID]
    );

    console.log(`⭐ [STAR_CLUB] ${newMemberCode} → Entry (Level 0)`);

    // Step 2: Saare existing L0 members ka counter +1 karo
    // Aur jo promote ho gaye unhe L1 par daal do
    await incrementAndCheckLevel(0, newMemberUUID);

  } catch (err) {
    console.error(`❌ [STAR_CLUB] Error for ${newMemberCode}:`, err.message);
  }
};

// ─────────────────────────────────────────────────────────────────────────────
//  Dashboard/API helper
// ─────────────────────────────────────────────────────────────────────────────
export const getStarClubInfo = (currentLevel, entryCount = 0) => {
  if (currentLevel === null || currentLevel === undefined) {
    return { inStarClub: false, currentLevel: null };
  }
  const current   = STAR_CLUB_LEVELS[currentLevel] || null;
  const next      = currentLevel < MAX_STAR_CLUB_LEVEL
    ? STAR_CLUB_LEVELS[currentLevel + 1] : null;
  const remaining = Math.max(0, PROMOTE_AFTER_COUNT - entryCount);

  return {
    inStarClub:         true,
    currentLevel,
    currentTitle:       current?.title || 'Star Club Entry',
    isMaxLevel:         currentLevel === MAX_STAR_CLUB_LEVEL,
    entryCount,
    remainingToPromote: remaining,
    nextLevel:          next ? { ...next, level: currentLevel + 1 } : null,
    allLevels:          STAR_CLUB_LEVELS.map(l => ({
      ...l,
      achieved:  l.level > 0 && l.level <= currentLevel,
      isCurrent: l.level === currentLevel,
    })),
  };
};