// Bug: coupons[key] with a truthiness check (prototype keys like "toString" pass), and percent 0 / min 0 handled by truthiness.export type CartItem = { sku: string; unitPriceCents: number; quantity: number };export type Coupon = | { kind: "percent"; percent: number } | { kind: "fixed"; amountCents: number; minSubtotalCents?: number };export type CartTotal = { subtotalCents: number; discountCents: number; totalCents: number };export type CartErrorKind = "invalid_item" | "unknown_coupon" | "coupon_not_applicable";export class CartError extends Error { readonly index?: number; readonly code?: string; constructor( public readonly kind: CartErrorKind, detail: { index?: number; code?: string } = {}, ) { super(kind); Object.assign(this, detail); }}export function cartTotal( items: CartItem[], couponCode: string | undefined, coupons: Record<string, Coupon>,): CartTotal { let subtotalCents = 0; items.forEach((item, index) => { if (!Number.isInteger(item.unitPriceCents) || item.unitPriceCents < 0 || !Number.isInteger(item.quantity) || item.quantity < 0) { throw new CartError("invalid_item", { index }); } subtotalCents += item.unitPriceCents * item.quantity; }); let discountCents = 0; const code = couponCode?.trim().toLowerCase(); if (code) { const coupon = coupons[code]; if (!coupon) throw new CartError("unknown_coupon", { code: couponCode }); if (coupon.kind === "percent") { discountCents = Math.floor((subtotalCents * coupon.percent) / 100); } else { if (coupon.minSubtotalCents && subtotalCents < coupon.minSubtotalCents) { throw new CartError("coupon_not_applicable", { code: couponCode }); } discountCents = Math.min(coupon.amountCents, subtotalCents); } } return { subtotalCents, discountCents, totalCents: subtotalCents - discountCents };}