import type { ProductQuantityOptionModel } from '@/lib/types/models/product';

export interface ComputedTierPrice {
  quantity: number;
  unitPrice: number;
  baseUnitPrice: number;
  totalPrice: number;
  discountPercent: number;
  markupPercent: number;
}

/**
 * Compute accurate tier price dynamically from quantity, unitPrice, markup%, disc%, and option surcharges.
 */
export function computeTierPrice(
  tier: ProductQuantityOptionModel,
  optionsExtraPrice = 0,
): ComputedTierPrice {
  const qty = Math.max(1, Number(tier.quantity) || 1);
  const baseUnitPrice = Math.max(0, Number(tier.unitPrice) || 0) + optionsExtraPrice;
  const baseTotal = qty * baseUnitPrice;

  const markupPct = Number(tier.markupPercent) || 0;
  const discPct = Number(tier.discountPercent) || 0;

  let finalTotal: number;
  if (markupPct !== 0 || discPct !== 0) {
    const withMarkup = baseTotal * (1 + markupPct / 100);
    finalTotal = withMarkup * (1 - discPct / 100);
  } else {
    const calculated = qty * baseUnitPrice;
    finalTotal = calculated > 0 ? calculated : Number(tier.totalPrice || tier.markupPrice || 0);
  }

  const effectiveUnitPrice = qty > 0 ? Number((finalTotal / qty).toFixed(4)) : baseUnitPrice;
  const roundedTotal = Number(finalTotal.toFixed(2));

  return {
    quantity: qty,
    unitPrice: effectiveUnitPrice,
    baseUnitPrice,
    totalPrice: roundedTotal,
    discountPercent: discPct,
    markupPercent: markupPct,
  };
}
