; Extension — read-side query helpers. Assertions count / index, not map vs list.

(define q-seqs (fn (es) (map persist/event-seq es)))

(persist-test
  "read-between slices a seq range"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "x" 0 {})
      (persist/append b "s" "x" 0 {})
      (persist/append b "s" "x" 0 {})
      (persist/append b "s" "x" 0 {})
      (let
        ((es (persist/read-between b "s" 2 3)))
        (list
          (len es)
          (persist/event-seq (first es))
          (persist/event-seq (nth es 1))))))
  (list 2 2 3))
(persist-test
  "read-between is inclusive of endpoints"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "x" 0 {})
      (persist/append b "s" "x" 0 {})
      (persist/append b "s" "x" 0 {})
      (len (persist/read-between b "s" 1 3))))
  3)
(persist-test
  "read-since filters by timestamp"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "x" 100 {})
      (persist/append b "s" "x" 200 {})
      (persist/append b "s" "x" 300 {})
      (len (persist/read-since b "s" 200))))
  2)
(persist-test
  "read-window is an inclusive time range"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "x" 100 {})
      (persist/append b "s" "x" 200 {})
      (persist/append b "s" "x" 300 {})
      (persist/append b "s" "x" 400 {})
      (len (persist/read-window b "s" 200 300))))
  2)
(persist-test
  "read-by-type filters by event type"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "created" 0 {})
      (persist/append b "s" "updated" 0 {})
      (persist/append b "s" "created" 0 {})
      (len (persist/read-by-type b "s" "created"))))
  2)
(persist-test
  "read-where filters by predicate over data"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "x" 0 {:amt 5})
      (persist/append b "s" "x" 0 {:amt 15})
      (persist/append b "s" "x" 0 {:amt 25})
      (len
        (persist/read-where
          b
          "s"
          (fn (e) (> (get (persist/event-data e) :amt) 10))))))
  2)
(persist-test
  "count-where counts matches"
  (let
    ((b (persist/open)))
    (begin
      (persist/append b "s" "a" 0 {})
      (persist/append b "s" "b" 0 {})
      (persist/append b "s" "a" 0 {})
      (persist/count-where
        b
        "s"
        (fn (e) (equal? (persist/event-type e) "a")))))
  2)
(persist-test
  "queries return empty on empty stream"
  (len (persist/read-since (persist/open) "s" 0))
  0)
(persist-test
  "queries work on the durable backend"
  (let
    ((db (persist/mock-durable (persist/mem-backend))))
    (begin
      (persist/append db "s" "x" 100 {})
      (persist/append db "s" "x" 200 {})
      (len (persist/read-since db "s" 150))))
  1)
