import type { InvoiceItem } from "@/types/invoice";

export function calculateItemTotal(quantity: number, unitPrice: number, discount = 0): number {
  const subtotal = quantity * unitPrice;
  const discountAmount = (subtotal * discount) / 100;
  return subtotal - discountAmount;
}

export function calculateInvoiceTotals(items: InvoiceItem[], taxRate = 21) {
  const subtotal = items.reduce((sum, item) => {
    return (
      sum + (item.quantity.amount * item.unit_price.amount) / Math.pow(10, item.unit_price.scale)
    );
  }, 0);

  const totalDiscount = items.reduce((sum, item) => {
    const itemSubtotal =
      (item.quantity.amount * item.unit_price.amount) / Math.pow(10, item.unit_price.scale);
    return sum + (itemSubtotal * item.discount.amount) / Math.pow(10, item.discount.scale) / 100;
  }, 0);

  const beforeTax = subtotal - totalDiscount;
  const taxAmount = (beforeTax * taxRate) / 100;
  const total = beforeTax + taxAmount;

  return {
    subtotal: Math.round(subtotal * 100),
    totalDiscount: Math.round(totalDiscount * 100),
    beforeTax: Math.round(beforeTax * 100),
    taxAmount: Math.round(taxAmount * 100),
    total: Math.round(total * 100),
  };
}

export function formatCurrency(amount: number, scale = 2, currency = "EUR"): string {
  const value = amount / Math.pow(10, scale);
  return new Intl.NumberFormat("es-ES", {
    style: "currency",
    currency: currency,
  }).format(value);
}
