// const buildLedger = (invoices, payments = []) => {
//   let balance = 0;
//   const rows = [];

//   // 1️⃣ Opening Balance
//   rows.push({
//     date: null,
//     type: "Opening",
//     reference: "-",
//     description: "Opening Balance",
//     debit: 0,
//     credit: 0,
//     balance,
//   });

//   invoices
//     .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
//     .forEach((inv) => {
//       // 2️⃣ Invoice (Debit)
//       balance += inv.grandTotal;

//       rows.push({
//         date: inv.generatedDate || inv.createdAt,
//         type: "Invoice",
//         reference: inv.invoiceNumber,
//         description: "Invoice Raised",
//         debit: inv.grandTotal,
//         credit: 0,
//         balance,
//       });

//       // 3️⃣ Payments (Credit)
//       const invPayments = payments
//         .filter((p) => String(p.invoiceId) === String(inv._id))
//         .sort((a, b) => new Date(a.paymentDate) - new Date(b.paymentDate));

//       invPayments.forEach((p) => {
//         balance -= p.amount;

//         rows.push({
//           date: p.paymentDate,
//           type: "Payment",
//           reference: p.paymentNumber,
//           description: "Payment Received",
//           debit: 0,
//           credit: p.amount,
//           balance,
//         });
//       });
//     });

//   return {
//     rows,
//     closingBalance: balance,
//   };
// };

// module.exports = buildLedger;

const buildLedger = (invoices, payments = []) => {
  let balance = 0;
  const events = [];

  // Opening balance
  events.push({
    date: null,
    type: "Opening",
    reference: "-",
    description: "Opening Balance",
    debit: 0,
    credit: 0,
  });

  // Invoice events
  invoices.forEach((inv) => {
    events.push({
      date: inv.generatedDate || inv.createdAt,
      type: "Invoice",
      reference: inv.invoiceNumber,
      description: "Invoice Raised",
      debit: inv.grandTotal,
      credit: 0,
    });
  });

  // Payment events (NO invoice loop)
  payments.forEach((p) => {
    events.push({
      date: p.paymentDate,
      type: "Payment",
      reference: p.paymentNumber || "-",
      description: "Payment Received",
      debit: 0,
      credit: p.amount,
    });
  });

  // Sort by date
  events.sort((a, b) => {
    if (!a.date) return -1;
    if (!b.date) return 1;
    return new Date(a.date) - new Date(b.date);
  });

  // Running balance
  const rows = events.map((e) => {
    balance += e.debit;
    balance -= e.credit;
    return { ...e, balance };
  });

  return {
    rows,
    closingBalance: balance,
  };
};

module.exports = buildLedger