;; lib/mod/tests/link.sx — Ext 4: report linking + dedup.

(define mod-lnk-count 0)
(define mod-lnk-pass 0)
(define mod-lnk-fail 0)
(define mod-lnk-failures (list))

(define
  mod-lnk-test!
  (fn
    (name got expected)
    (begin
      (set! mod-lnk-count (+ mod-lnk-count 1))
      (if
        (= got expected)
        (set! mod-lnk-pass (+ mod-lnk-pass 1))
        (begin
          (set! mod-lnk-fail (+ mod-lnk-fail 1))
          (append!
            mod-lnk-failures
            (str name "\n    expected: " expected "\n    got:      " got)))))))

;; ── link-key + dedup ──

(define mod-lnk-a (mod/mk-report "r1" "alice" "bob" "this is spam"))
(define mod-lnk-a2 (mod/mk-report "r2" "alice" "bob" "THIS IS SPAM"))
(define mod-lnk-b (mod/mk-report "r3" "carol" "bob" "abuse"))
(define mod-lnk-c (mod/mk-report "r4" "alice" "eve" "this is spam"))

(mod-lnk-test!
  "identical reports share a link key (case-insensitive reason)"
  (= (mod/link-key mod-lnk-a) (mod/link-key mod-lnk-a2))
  true)
(mod-lnk-test!
  "different reporter → different key"
  (= (mod/link-key mod-lnk-a) (mod/link-key mod-lnk-b))
  false)
(mod-lnk-test!
  "different subject → different key"
  (= (mod/link-key mod-lnk-a) (mod/link-key mod-lnk-c))
  false)

(define mod-lnk-set (list mod-lnk-a mod-lnk-a2 mod-lnk-b mod-lnk-c))
(mod-lnk-test!
  "dedup collapses identical reports"
  (len (mod/dedup-reports mod-lnk-set))
  3)
(mod-lnk-test!
  "duplicate-count counts collapsed"
  (mod/duplicate-count mod-lnk-set)
  1)
(mod-lnk-test!
  "dedup of all-distinct keeps all"
  (len (mod/dedup-reports (list mod-lnk-a mod-lnk-b mod-lnk-c)))
  3)

;; ── Prolog-backed relational linking ──

(mod-lnk-test!
  "related-ids finds all reports about subject"
  (len (mod/related-ids "bob" mod-lnk-set))
  3)
(mod-lnk-test!
  "related-ids returns the ids"
  (mod/related-ids "eve" mod-lnk-set)
  (list "r4"))
(mod-lnk-test!
  "related-ids empty for unknown subject"
  (mod/related-ids "nobody" mod-lnk-set)
  (list))

;; reporters: bob reported by alice (x2) + carol → 3 raw, 2 distinct
(mod-lnk-test!
  "reporters-of counts all reports"
  (len (mod/reporters-of "bob" mod-lnk-set))
  3)
(mod-lnk-test!
  "distinct reporters-of dedups reporters"
  (len (mod/distinct-reporters-of "bob" mod-lnk-set))
  2)
(mod-lnk-test!
  "distinct utility removes dups"
  (mod/distinct (list "a" "b" "a" "c" "b"))
  (list "a" "b" "c"))

(define mod-link-tests-run! (fn () {:failures mod-lnk-failures :total mod-lnk-count :passed mod-lnk-pass :failed mod-lnk-fail}))
