import { MoneyDTO } from "@erp/core";
import { useMoney, usePercentage, useQuantity } from "@erp/core/hooks";
import { useMemo } from "react";
import { InvoiceItemFormData } from "../../schemas";

export type InvoiceTotals = Readonly<{
  subtotal: number;
  discountTotal: number;
  taxableBase: number;
  taxes: number;
  total: number;

  subtotalDTO: MoneyDTO;
  discountTotalDTO: MoneyDTO;
  taxableBaseDTO: MoneyDTO;
  taxesDTO: MoneyDTO;
  totalDTO: MoneyDTO;

  // número de líneas válidas consideradas
  itemCount: number;
}>;

/**
 * Calcula los totales generales de la factura a partir de sus líneas.
 */
export function useCalcInvoiceTotals(items: InvoiceItemFormData[] | undefined): InvoiceTotals {
  const money = useMoney();
  const qty = useQuantity();
  const pct = usePercentage();

  return useMemo<InvoiceTotals>(() => {
    if (!items?.length) {
      const zero = money.fromNumber(0);
      return {
        subtotal: 0,
        discountTotal: 0,
        taxableBase: 0,
        taxes: 0,
        total: 0,
        subtotalDTO: zero,
        discountTotalDTO: zero,
        taxableBaseDTO: zero,
        taxesDTO: zero,
        totalDTO: zero,
        itemCount: 0,
      };
    }

    let subtotal = 0;
    let discountTotal = 0;
    let taxableBase = 0;
    let taxes = 0;
    let total = 0;

    for (const item of items) {
      const quantity = qty.toNumber(item.quantity);
      const unit = money.toNumber(item.unit_amount);
      const discountPct = pct.toNumber(item.discount_percentage);

      const lineSubtotal = quantity * unit;
      const lineDiscount = lineSubtotal * (discountPct / 100);
      const lineTaxable = lineSubtotal - lineDiscount;
      const lineTaxes = 0; // ← ajusta si aplicas IVA o impuestos reales
      const lineTotal = lineTaxable + lineTaxes;

      subtotal += lineSubtotal;
      discountTotal += lineDiscount;
      taxableBase += lineTaxable;
      taxes += lineTaxes;
      total += lineTotal;
    }

    return {
      subtotal,
      discountTotal,
      taxableBase,
      taxes,
      total,
      subtotalDTO: money.fromNumber(subtotal),
      discountTotalDTO: money.fromNumber(discountTotal),
      taxableBaseDTO: money.fromNumber(taxableBase),
      taxesDTO: money.fromNumber(taxes),
      totalDTO: money.fromNumber(total),
      itemCount: items.length,
    };
  }, [items, money, qty, pct]);
}
