// ============================================================
//  pppHelper.js  –  Partner Package Income (PPP) Engine
// ============================================================
//
//  Admin ek amount aur ek package select karta hai.
//  Jitne bhi members us package par YA US SE UPAR hain,
//  unhe barabar barabar amount distribute hoti hai.
//
//  Formula:
//    per_member_income = admin_amount / eligible_member_count
//
//  Eligibility:
//    member.plan >= selected_plan  (plan index comparison)
//    member.status = 'Active'
//
//  DB Column: members.ppp_income  (DECIMAL, already existing ya add karna hoga)
//  Transaction type: 'PPP_INCOME'
// ============================================================

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

const PLAN_SLABS = [1500, 3000, 6000, 12000, 24000, 48000, 96000];
 
const getPlanIndex = (planAmount) => PLAN_SLABS.indexOf(parseFloat(planAmount));
 
// ─────────────────────────────────────────────
//  PREVIEW — no DB writes, just calculates
// ─────────────────────────────────────────────
export const previewPPPIncome = async (selectedPlan, totalAmount) => {
  const selectedPlanIdx = getPlanIndex(selectedPlan);
  if (selectedPlanIdx === -1) throw new Error(`Invalid plan amount: ${selectedPlan}`);
  if (!totalAmount || parseFloat(totalAmount) <= 0)
    throw new Error('Total amount must be greater than 0');
 
  const eligiblePlans = PLAN_SLABS.slice(selectedPlanIdx);
  const placeholders  = eligiblePlans.map(() => '?').join(', ');
 
  const [eligibleMembers] = await db.query(
    `SELECT id, member_id, full_name, plan
       FROM members
      WHERE status = 'Active'
        AND plan IN (${placeholders})
      ORDER BY plan ASC, member_id ASC`,
    eligiblePlans
  );
 
  const eligibleCount   = eligibleMembers.length;
  const amount          = parseFloat(totalAmount);
  const perMemberAmount = eligibleCount > 0
    ? parseFloat((amount / eligibleCount).toFixed(2))
    : 0;
 
  return {
    selectedPlan,
    totalAmount: amount,
    eligibleCount,
    perMemberAmount,
    eligibleMembers: eligibleMembers.map((m) => ({
      id:        m.id,
      member_id: m.member_id,
      full_name: m.full_name,
      plan:      m.plan,
      income:    perMemberAmount,
    })),
  };
};
 
// ─────────────────────────────────────────────
//  DISTRIBUTE — credits wallet + ppp_income + total_income
// ─────────────────────────────────────────────
export const distributePPPIncome = async (selectedPlan, totalAmount, adminNote = '') => {
  const preview = await previewPPPIncome(selectedPlan, totalAmount);
 
  if (preview.eligibleCount === 0)
    return { success: false, message: 'No eligible members found for this plan', ...preview };
 
  const { perMemberAmount, eligibleMembers } = preview;
 
  const conn = await db.getConnection();
  try {
    await conn.beginTransaction();
 
    const description =
      `Partner Package Income | Plan ₹${selectedPlan}+ | ` +
      `Total ₹${totalAmount} / ${preview.eligibleCount} members = ₹${perMemberAmount} each` +
      (adminNote ? ` | Note: ${adminNote}` : '');
 
    for (const member of eligibleMembers) {
      await conn.query(
        `UPDATE members
            SET wallet_balance = wallet_balance + ?,
                ppp_income     = ppp_income     + ?,
                total_income   = total_income   + ?,
                updated_at     = NOW()
          WHERE id = ?`,
        [perMemberAmount, perMemberAmount, perMemberAmount, member.id]
      );
 
      await conn.query(
        `INSERT INTO transactions
           (user_type, user_id, user_member_id, transaction_type,
            amount, description, order_id, created_at)
         VALUES ('member', ?, ?, 'PPP_INCOME', ?, ?, NULL, NOW())`,
        [member.id, member.member_id, perMemberAmount, description]
      );
    }
 
    await conn.commit();
    console.log(`✅ [PPP_INCOME] ₹${perMemberAmount} × ${preview.eligibleCount} members | Total ₹${totalAmount}`);
 
    return {
      success:        true,
      message:        `PPP Income distributed to ${preview.eligibleCount} members`,
      selectedPlan,
      totalAmount:    parseFloat(totalAmount),
      eligibleCount:  preview.eligibleCount,
      perMemberAmount,
    };
  } catch (err) {
    await conn.rollback();
    console.error('❌ [PPP_INCOME] error:', err.message);
    throw err;
  } finally {
    conn.release();
  }
};