;; lib/commerce/api.sx — public commerce surface.
;;
;; A session bundles a pricing context with a cart: {:ctx CTX :cart CART}.
;; All operations are pure and return a new session. The total and the
;; per-line breakdown are deterministic functions of (ctx, cart).
;;
;; commerce-checkout is a Phase-3 stub — the order lifecycle is a durable
;; flow that suspends at the SumUp payment boundary.

(define commerce-session (fn (ctx) {:cart empty-cart :ctx ctx}))

(define commerce-ctx (fn (sess) (get sess :ctx)))
(define commerce-cart (fn (sess) (get sess :cart)))
(define commerce-lines (fn (sess) (cart-lines (get sess :cart))))
(define commerce-count (fn (sess) (cart-count (get sess :cart))))

(define
  commerce-add
  (fn
    (sess sku variant qty)
    (assoc sess :cart (cart-add (get sess :cart) sku variant qty))))

(define
  commerce-remove
  (fn
    (sess sku variant)
    (assoc sess :cart (cart-remove (get sess :cart) sku variant))))

(define
  commerce-set-qty
  (fn
    (sess sku variant qty)
    (assoc sess :cart (cart-set-qty (get sess :cart) sku variant qty))))

;; True when the sku exists in the session's catalog snapshot.
(define
  commerce-can-add?
  (fn (sess sku) (catalog-has? (ctx-catalog (get sess :ctx)) sku)))

(define
  commerce-total
  (fn (sess) (cart-total (get sess :ctx) (get sess :cart))))

;; Per-line audit breakdown — the "which line contributed what" view.
(define
  line-detail
  (fn (ctx line) (let ((cat (ctx-catalog ctx))) {:sku (line-sku line) :unit (line-unit-price cat (line-sku line) (line-variant line)) :qty (line-qty line) :variant (line-variant line) :extended (line-extended cat line) :tax (line-tax ctx line)})))

(define
  commerce-explain
  (fn
    (sess)
    (map (fn (l) (line-detail (get sess :ctx) l)) (get sess :cart))))

;; Phase 3 — order lifecycle flow (reserve -> pay -> fulfil) lands here.
(define commerce-checkout (fn (sess) {:note "order lifecycle flow lands in Phase 3" :phase 3 :status :not-implemented}))
