// Pure quantity-tier math. ZERO env / cloudflare:workers / DOM / Date deps —
// imported by both the Worker (cart-resolver, decide) and the browser island,
// which is what guarantees client/server price parity.

export interface QtyTier {
  minQty: number;
  discountPercent: number;
}

export interface QtyTierResult {
  effectiveUnitAgorot: number; // per-unit price after the applied tier
  lineTotalAgorot: number; // effectiveUnitAgorot * qty
  tierApplied: QtyTier | null; // null = no tier matched
}

/**
 * Applies the single highest-discount tier whose minQty <= qty to the WHOLE
 * quantity. unitAgorot is the SKU discountedPrice in integer agorot.
 */
export function applyQtyTier(
  unitAgorot: number,
  qty: number,
  tiers: QtyTier[],
): QtyTierResult {
  const tier =
    tiers
      .filter((t) => t.minQty <= qty)
      .sort((a, b) => b.discountPercent - a.discountPercent)[0] ?? null;

  const effectiveUnitAgorot = tier
    ? Math.round((unitAgorot * (100 - tier.discountPercent)) / 100)
    : unitAgorot;

  return {
    effectiveUnitAgorot,
    lineTotalAgorot: effectiveUnitAgorot * qty,
    tierApplied: tier,
  };
}
