import { Tax, Taxes } from "@erp/core/api";
import { ItemAmount } from "../../value-objects";

export type ItemTaxTotal = {
  tax: Tax;
  taxableAmount: ItemAmount;
  taxesAmount: ItemAmount;
};

export class ItemTaxes extends Taxes {
  constructor(items: Tax[] = [], totalItems: number | null = null) {
    super(items, totalItems);
  }

  public getTaxesAmount(taxableAmount: ItemAmount): ItemAmount {
    return this.getAll().reduce(
      (total, tax) => total.add(taxableAmount.percentage(tax.percentage)),
      ItemAmount.zero(taxableAmount.currencyCode)
    );
  }

  public getTaxesAmountByTaxCode(taxCode: string, taxableAmount: ItemAmount): ItemAmount {
    const currencyCode = taxableAmount.currencyCode;

    return this.filter((itemTax) => itemTax.code === taxCode).reduce((totalAmount, itemTax) => {
      return taxableAmount.percentage(itemTax.percentage).add(totalAmount);
    }, ItemAmount.zero(currencyCode));
  }

  public getTaxesAmountByTaxes(taxableAmount: ItemAmount): ItemTaxTotal[] {
    return this.getAll().map((taxItem) => ({
      taxableAmount,
      tax: taxItem,
      taxesAmount: this.getTaxesAmountByTaxCode(taxItem.code, taxableAmount),
    }));
  }

  public getCodesToString(): string {
    return this.getAll()
      .map((taxItem) => taxItem.code)
      .join(", ");
  }
}
