;; lib/mod/sla.sx — service-level sweep over pending lifecycle cases.
;;
;; Composes the Phase-3 lifecycle with the Ext-12 time dimension: a case left in a
;; pending state (open / triaged / appealed) past a deadline has breached SLA and
;; should resurface. A timed-case pairs a case with the tick it entered its
;; current state (the caller stamps this — the lifecycle stays timeless and pure).
;; Terminal states (decided / final) never breach.

(define mod/pending-states (list "open" "triaged" "appealed"))
(define mod/pending-state? (fn (s) (mod/member? s mod/pending-states)))

(define mod/mk-timed-case (fn (c entered-at) {:entered-at entered-at :case c}))
(define mod/tc-case (fn (tc) (get tc :case)))
(define mod/tc-entered-at (fn (tc) (get tc :entered-at)))

(define
  mod/overdue?
  (fn
    (tc now deadline)
    (if
      (mod/pending-state? (mod/case-state (mod/tc-case tc)))
      (< deadline (- now (mod/tc-entered-at tc)))
      false)))

(define
  mod/sla-sweep
  (fn
    (timed-cases now deadline)
    (reduce
      (fn
        (acc tc)
        (if
          (mod/overdue? tc now deadline)
          (append
            acc
            (list (mod/report-id (mod/case-report (mod/tc-case tc)))))
          acc))
      (list)
      timed-cases)))

(define
  mod/overdue-count
  (fn
    (timed-cases now deadline)
    (len (mod/sla-sweep timed-cases now deadline))))

(define mod/age (fn (tc now) (- now (mod/tc-entered-at tc))))
