// services/invoice/invoice.calculation.js
exports.calculateInvoiceFromTask = async (task, tax, discount) => {
  const base = task.serviceCost;

  const discountAmount =
    discount?.type === "PERCENTAGE"
      ? (base * discount.value) / 100
      : discount?.value || 0;

  const taxableAmount = base - discountAmount;

  const cgstAmount = (tax?.rates?.cgst || 0) * taxableAmount / 100;
  const sgstAmount = (tax?.rates?.sgst || 0) * taxableAmount / 100;

  const totalTax = cgstAmount + sgstAmount;
  const grandTotal = taxableAmount + totalTax;

  return {
    items: [
      {
        description: task.serviceName,
        quantity: 1,
        rate: base,
        baseAmount: base,
        discount: {
          name: discount?.name,
          type: discount?.type,
          value: discount?.value,
          amount: discountAmount,
        },
        tax: {
          name: tax?.name,
          cgstPercent: tax?.rates?.cgst,
          sgstPercent: tax?.rates?.sgst,
          cgstAmount,
          sgstAmount,
          totalTax,
        },
        total: grandTotal,
      },
    ],
    subTotal: base,
    totalDiscount: discountAmount,
    totalTax,
    grandTotal,
  };
};
