import { Ok, Err, type Option, type Result } from "@tsus/runtime";export type CartItem = { sku: string; unitPriceCents: number; quantity: number };export type Coupon = | { kind: "percent"; percent: number } | { kind: "fixed"; amountCents: number; minSubtotalCents: Option<number> };export type CartTotal = { subtotalCents: number; discountCents: number; totalCents: number };export type CartError = | { kind: "invalid_item"; index: number } | { kind: "unknown_coupon"; code: string } | { kind: "coupon_not_applicable"; code: string };const isCount = (v: unknown): boolean => typeof v === "number" && Number.isInteger(v) && v >= 0;const subtotalOf = (items: CartItem[]): Result<number, CartError> => { let total = 0; for (let index = 0; index < items.length; index += 1) { const item = items[index]; if (!isCount(item.unitPriceCents) || !isCount(item.quantity)) { return Err({ kind: "invalid_item", index }); } total += item.unitPriceCents * item.quantity; } return Ok(total);};const discountFor = (coupon: Coupon, subtotal: number, code: string): Result<number, CartError> => coupon.kind === "percent" ? Ok(Math.floor((subtotal * coupon.percent) / 100)) : coupon.minSubtotalCents.map((min) => subtotal < min).unwrapOr(false) ? Err({ kind: "coupon_not_applicable", code }) : Ok(Math.min(coupon.amountCents, subtotal));const applyCode = (code: string, subtotal: number, coupons: Record<string, Coupon>): Result<number, CartError> => { const key = code.trim().toLowerCase(); if (key === "") { return Ok(0); } return Object.hasOwn(coupons, key) ? discountFor(coupons[key], subtotal, code) : Err({ kind: "unknown_coupon", code });};export const cartTotal = ( items: CartItem[], couponCode: Option<string>, coupons: Record<string, Coupon>,): Result<CartTotal, CartError> => subtotalOf(items).andThen((subtotalCents) => match (couponCode) { None => Ok(0), Some(code) => applyCode(code, subtotalCents, coupons), }.map((discountCents) => ({ subtotalCents, discountCents, totalCents: subtotalCents - discountCents })), );