/**
 * CartCheckout domain events — discriminated union.
 *
 * Drives cart batch validation; per-line decisions are produced by `decide`
 * and persisted by `applyEffects`.
 *
 *   BATCH_VALIDATING + lines_validated(all_ok)   → ACCEPTED
 *     effects: per line [reserve-line], finalize [clear-cart]
 *
 *   BATCH_VALIDATING + lines_validated(any_stale) → REJECTED
 *     error: STALE_ITEMS (lines split into removed[] / updated[])
 *
 * Pure module: no imports from @/server/db, do-client, outbox-producer, payments, fetch.
 */

export type CartLineState = 'OK' | 'EXPIRED' | 'INACTIVE' | 'SOLD_OUT' | 'QTY_CLAMPED';

export interface ValidatedCartLine {
  dealId: string;
  /** SKU selected by the customer. Null for pre-variant cart items (legacy). */
  dealSkuId: string | null;
  vendorId: string;
  dealTitle: string;
  qty: number;
  /** Clamped quantity per maxPerUser and remaining stock — same as final qty when OK. */
  clampedQty: number;
  /** Stock that was available at validation time (quantityTotal - quantitySold). */
  availableStock: number;
  dealState: string;
  isExpired: boolean;
  discountedPrice: string;
  commissionRate: string;
  /** Quantity-break tiers for this line's SKU; empty = no qty-tier feature. */
  qtyTiers: { minQty: number; discountPercent: number }[];
  windowEnd: Date | null;
  /** Effective expiry for this purchase row (windowEnd or +180d from event.at). */
  expiresAt: Date;
  lineState: CartLineState;
}

export type CartCheckoutEvent = {
  kind: 'lines_validated';
  userId: string;
  paymentMethodId?: string;
  idempotencyKey: string;
  lines: ValidatedCartLine[];
  at: Date;
};
