// ─────────────────────────────────────────────────────────────────────────────
//  royaltyHelper.js
//  Royalty Income System
//
//  Qualification Rule:
//    Jis member ne apni registration ke 15 din ke andar
//    10 direct members sponsor kar liye → wo ROYALTY QUALIFIED ho jaata hai.
//
//  Income Rule (post-qualification):
//    Jab bhi company mein koi bhi naya member approve ho,
//    us naye member ke plan amount ka 1% → har ek royalty-qualified
//    member ke roylty_income + wallet_balance + total_income mein jaata hai.
//
//  DB Column Required:
//    ALTER TABLE members
//    ADD COLUMN royalty_qualified tinyint(1) NOT NULL DEFAULT 0;
// ─────────────────────────────────────────────────────────────────────────────

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

const ROYALTY_PERCENT     = 0.01;   // 1%
const QUALIFY_DIRECT_COUNT = 10;    // kitne direct chahiye
const QUALIFY_DAYS         = 15;    // kitne din ke andar

// ─────────────────────────────────────────────────────────────────────────────
//  Export 1: checkAndGrantRoyaltyQualification
//
//  Call karo jab bhi kisi member ka total_direct badhta hai.
//  Agar wo abhi qualified nahi hai aur conditions meet ho rahi hain
//  → royalty_qualified = 1 kar do.
//
//  @param sponsorMemberId  – member_id (e.g. "RV001") of the sponsor
// ─────────────────────────────────────────────────────────────────────────────
export const checkAndGrantRoyaltyQualification = async (sponsorMemberId) => {
  try {
    // Fetch sponsor
    const [rows] = await db.query(
      `SELECT id, member_id, total_direct, royalty_qualified, created_at
         FROM members
        WHERE member_id = ?`,
      [sponsorMemberId]
    );

    if (!rows.length) {
      console.warn(`⚠️ [ROYALTY] Sponsor not found: ${sponsorMemberId}`);
      return;
    }

    const sponsor = rows[0];

    // Already qualified — kuch karne ki zarurat nahi
    if (sponsor.royalty_qualified === 1) return;

    // Check: total_direct >= 10?
    if (parseInt(sponsor.total_direct) < QUALIFY_DIRECT_COUNT) return;

    // Check: kya 10th direct 15 din ke andar aaya?
    // Hum count karte hain kitne active direct members hain
    // jo sponsor ki registration ke 15 din ke andar approve hue
    const cutoffDate = new Date(sponsor.created_at);
    cutoffDate.setDate(cutoffDate.getDate() + QUALIFY_DAYS);

    const [countRows] = await db.query(
      `SELECT COUNT(*) AS cnt
         FROM members
        WHERE sponsor_id  = ?
          AND status      = 'Active'
          AND created_at <= ?`,
      [sponsorMemberId, cutoffDate]
    );

    const directWithinWindow = parseInt(countRows[0].cnt);

    if (directWithinWindow < QUALIFY_DIRECT_COUNT) {
      console.log(
        `ℹ️ [ROYALTY] ${sponsorMemberId} has ${directWithinWindow} directs within ${QUALIFY_DAYS} days ` +
        `(needs ${QUALIFY_DIRECT_COUNT}) → not qualified yet`
      );
      return;
    }

    // ✅ Qualification achieved — mark in DB
    await db.query(
      `UPDATE members
          SET royalty_qualified = 1,
              updated_at        = NOW()
        WHERE id = ?`,
      [sponsor.id]
    );

    console.log(
      `🏆 [ROYALTY] ${sponsorMemberId} ROYALTY QUALIFIED! ` +
      `${directWithinWindow} directs within ${QUALIFY_DAYS} days.`
    );

  } catch (err) {
    console.error(`❌ [ROYALTY] checkAndGrantRoyaltyQualification error:`, err.message);
  }
};

// ─────────────────────────────────────────────────────────────────────────────
//  Export 2: distributeRoyaltyIncome
//
//  Jab bhi koi naya member approve ho → is function ko call karo.
//  Saare royalty-qualified members ko new member ke plan ka 1% milega.
//
//  @param newMemberId  – UUID (id) of the newly approved member
// ─────────────────────────────────────────────────────────────────────────────
export const distributeRoyaltyIncome = async (newMemberId) => {
  try {
    // Fetch new member's plan
    const [memberRows] = await db.query(
      `SELECT id, member_id, plan FROM members WHERE id = ?`,
      [newMemberId]
    );

    if (!memberRows.length) {
      console.warn(`⚠️ [ROYALTY] New member not found: ${newMemberId}`);
      return;
    }

    const newMember = memberRows[0];
    const planAmount = parseFloat(newMember.plan);

    if (!planAmount || planAmount <= 0) {
      console.warn(`⚠️ [ROYALTY] Invalid plan for ${newMember.member_id}: ${newMember.plan}`);
      return;
    }

    const royaltyAmount = planAmount * ROYALTY_PERCENT;

    // Fetch ALL royalty-qualified members
    // (exclude the new member themselves — edge case)
    const [qualifiedMembers] = await db.query(
      `SELECT id, member_id
         FROM members
        WHERE royalty_qualified = 1
          AND id != ?
          AND status = 'Active'`,
      [newMemberId]
    );

    if (!qualifiedMembers.length) {
      console.log(`ℹ️ [ROYALTY] No royalty-qualified members found. Skipping.`);
      return;
    }

    console.log(
      `💎 [ROYALTY] Distributing ₹${royaltyAmount.toLocaleString('en-IN')} ` +
      `(1% of ₹${planAmount.toLocaleString('en-IN')}) ` +
      `to ${qualifiedMembers.length} qualified member(s) | from ${newMember.member_id}`
    );

    // Credit each qualified member
    for (const qm of qualifiedMembers) {
      await db.query(
        `UPDATE members
            SET roylty_income   = roylty_income   + ?,
                wallet_balance  = wallet_balance  + ?,
                total_income    = total_income    + ?,
                updated_at      = NOW()
          WHERE id = ?`,
        [royaltyAmount, royaltyAmount, royaltyAmount, qm.id]
      );

      const description =
        `Royalty Income | New member ${newMember.member_id} joined ` +
        `| Plan ₹${planAmount.toLocaleString('en-IN')} × 1% = ₹${royaltyAmount.toLocaleString('en-IN')}`;

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

      console.log(
        `✅ [ROYALTY] ₹${royaltyAmount.toLocaleString('en-IN')} → ${qm.member_id} | from ${newMember.member_id}`
      );
    }

    console.log(`🎉 [ROYALTY] Distribution complete for ${newMember.member_id}`);

  } catch (err) {
    console.error(`❌ [ROYALTY] distributeRoyaltyIncome error:`, err.message);
  }
};