import { TaxType } from "modules/system/taxes/types";
import { ItemType, OrderType } from "pages/pos/orders/types";

/**
 * To aggregate all the items to make sure to show totals over all the order not only one order
 * @param activeTab
 * @param orders
 * @param items
 * @returns
 */
export function prepareTheCompletedList(
  activeTab: string,
  orders: OrderType[],
  items: ItemType[]
) {
  let theCompletedList: ItemType[] | undefined = [];
  if (activeTab == "0")
    theCompletedList = [...(theCompletedList || []), ...(items || [])];

  if (activeTab)
    orders.forEach((o) => {
      if (o.id == activeTab)
        theCompletedList = [...(theCompletedList || []), ...(items || [])];
      else theCompletedList = [...(theCompletedList || []), ...(o.items || [])];
    });
  else {
    theCompletedList = items;
  }
  return theCompletedList;
}

export function calculateSubTotal(items: Array<ItemType>) {
  let subTotalAmount = 0;
  items?.forEach((i) => {
    subTotalAmount += Number(i.unit_price) * (i?.quantity || 0);
  });
  return subTotalAmount;
}

export function calculateDiscount(
  subTotalAmount: number,
  discount: {
    type: "PERCENTAGE" | "FIXED";
    value: number;
  }
) {
  let discountAmount = 0;
  if (discount.type === "PERCENTAGE") {
    discountAmount += (Number(discount.value) / 100) * subTotalAmount;
  }
  if (discount.type === "FIXED") {
    discountAmount += Number(discount.value);
  }
  return Math.ceil(discountAmount / 100) * 100;
}

export function calculateTax(subTotalAmount: number, taxes: Array<TaxType>) {
  const newTaxes = [...taxes];
  let taxesAmount = 0;
  newTaxes
    .sort((a, b) => (a.from_tax?.id || 0) - (b.from_tax?.id || 0))
    .forEach((tax: TaxType) => {
      taxesAmount +=
        Math.ceil(calculateTaxAmount(subTotalAmount, tax) / 100) * 100;
    });

  return taxesAmount;
}

export function calculateSpecificTax(
  subTotalAmount: number,
  taxes: Array<TaxType>,
  tax: TaxType
) {
  let taxesAmount = 0;

  const newTaxes = [...taxes];
  newTaxes
    .sort((a, b) => (a.from_tax?.id || 0) - (b.from_tax?.id || 0))
    .forEach((t: TaxType) => {
      if (t.id === tax.id)
        taxesAmount +=
          Math.ceil(calculateTaxAmount(subTotalAmount, tax) / 100) * 100;
    });

  return taxesAmount;
}

export function calculateTaxAmount(amount: number, tax: TaxType) {
  const value = tax.value;
  let total = amount;

  if (tax.from_tax !== null) {
    total = calculateTaxAmount(total, tax.from_tax);
  }

  total = tax.type === "FIXED" ? value : (value * total) / 100;

  return total;
}

export function calculateGrandTotalAmount(
  subTotalAmount: number,
  taxAmount: number,
  discountAmount: number
) {
  return subTotalAmount + taxAmount - discountAmount;
}
