const calculateInvoiceTotals = (items = [], discount = null) => {
  let subTotal = 0;
  let totalTax = 0;
  let totalDiscount = 0;

  // 1️⃣ Calculate subtotal & tax from items
  items.forEach((item) => {
    const amount = Number(item.amount || 0);
    subTotal += amount;

    if (item.tax) {
      totalTax += Number(item.tax.totalTax || 0);
    }
  });

  // 2️⃣ Apply discount
  if (discount) {
    if (discount.type === "PERCENTAGE") {
      totalDiscount = (subTotal * discount.value) / 100;
    } else if (discount.type === "FLAT") {
      totalDiscount = discount.value;
    }
  }

  // 3️⃣ Prevent over-discount
  if (totalDiscount > subTotal) {
    totalDiscount = subTotal;
  }

  // 4️⃣ Final total
  const grandTotal = subTotal - totalDiscount + totalTax;

  return {
    subTotal,
    totalDiscount,
    totalTax,
    grandTotal,
  };
};

module.exports = calculateInvoiceTotals;
