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

/**
 * Calcula totales derivados de un ítem de factura
 */

export type InvoiceItemTotals = Readonly<{
  // valores base ya normalizados a number
  quantity: number;
  unitAmount: number;
  discountPercent: number;

  // desgloses numéricos
  subtotal: number; // qty * unit
  discountAmount: number; // subtotal * (discountPercent/100)
  taxableBase: number; // subtotal - discountAmount
  taxes: number; // por ahora 0 (o calcula según tax_codes si lo necesitas)
  total: number; // taxableBase + taxes

  // equivalentes en MoneyDTO (misma divisa/escala que useMoney)
  subtotalDTO: MoneyDTO;
  discountAmountDTO: MoneyDTO;
  taxableBaseDTO: MoneyDTO;
  taxesDTO: MoneyDTO;
  totalDTO: MoneyDTO;
}>;
/**
 * Calcula totales derivados de una línea de factura usando tus hooks de Money/Quantity/Percentage.
 */
export function useCalcInvoiceItemTotals(item?: InvoiceItemFormData): InvoiceItemTotals {
  const moneyHelper = useMoney();
  const qtyHelper = useQuantity();
  const pctHelper = usePercentage();

  return useMemo<InvoiceItemTotals>(() => {
    // valores base
    const quantity = item ? qtyHelper.toNumber(item.quantity) : 0;
    const unitAmount = item ? moneyHelper.toNumber(item.unit_amount) : 0;
    const discountPercent = item ? pctHelper.toNumber(item.discount_percentage) : 0;

    // cálculos
    const subtotal = quantity * unitAmount;
    const discountAmount = subtotal * (discountPercent / 100);
    const taxableBase = subtotal - discountAmount;

    // impuestos (ajústalo si quieres aplicar tax_codes)
    const taxes = 0;

    const total = taxableBase + taxes;

    // DTOs
    const subtotalDTO = moneyHelper.fromNumber(subtotal);
    const discountAmountDTO = moneyHelper.fromNumber(discountAmount);
    const taxableBaseDTO = moneyHelper.fromNumber(taxableBase);
    const taxesDTO = moneyHelper.fromNumber(taxes);
    const totalDTO = moneyHelper.fromNumber(total);

    return {
      quantity,
      unitAmount,
      discountPercent,
      subtotal,
      discountAmount,
      taxableBase,
      taxes,
      total,
      subtotalDTO,
      discountAmountDTO,
      taxableBaseDTO,
      taxesDTO,
      totalDTO,
    };
  }, [item, moneyHelper, qtyHelper, pctHelper]);
}
