#!/usr/bin/env bash
# tests/trust_filter/run-tests.sh -- fixtures for scripts/trust_filter.py (S4).
# Covers the three real call shapes it consolidates + parse-error + bad-fields.
# No cloud access.
set -uo pipefail
SD="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; PY="$SD/../../scripts/trust_filter.py"
P=0; F=0
ck(){ local name="$1" want="$2" got="$3"; if [ "$got" = "$want" ]; then echo "PASS: $name"; P=$((P+1)); else echo "FAIL: $name"; echo "  want: [$want]"; echo "  got:  [$got]"; F=$((F+1)); fi; }

# fixture: three trusts; trustors u1, u2, u3
J='[{"ID":"t1","Trustor User ID":"u1","Trustee User ID":"e1"},
    {"ID":"t2","Trustor User ID":"u2","Trustee User ID":"e2"},
    {"ID":"t3","Trustor User ID":"u3","Trustee User ID":"e3"}]'

# 1) offboard sweep: all trusts, ID + Trustee, no filter
ck all-id-trustee "$(printf 't1 e1\nt2 e2\nt3 e3')" "$(printf '%s' "$J" | python3 "$PY" --fields ID,TRUSTEE)"

# 2) offboard audit: filter by a uid set (space-separated), 3 fields
ck filter-set "$(printf 't1 u1 e1\nt3 u3 e3')" "$(printf '%s' "$J" | python3 "$PY" --fields ID,TRUSTOR,TRUSTEE --trustor-in "u1 u3")"

# 2b) comma-separated uid set also accepted
ck filter-set-comma "t2 u2 e2" "$(printf '%s' "$J" | python3 "$PY" --fields ID,TRUSTOR,TRUSTEE --trustor-in "u2,uX")"

# 3) acceptance: single trustor, first trustee only, empty-on-error
ck accept-hit "e2" "$(printf '%s' "$J" | python3 "$PY" --fields TRUSTEE --trustor-in "u2" --first --error-token '')"
ck accept-miss "" "$(printf '%s' "$J" | python3 "$PY" --fields TRUSTEE --trustor-in "nope" --first --error-token '')"

# 4) parse error: default token surfaces (grep-detectable), empty token stays silent
ERR="$(printf 'not json' | python3 "$PY" --fields ID,TRUSTEE)"
case "$ERR" in trust-parse-error*) echo "PASS: parse-error-token"; P=$((P+1));; *) echo "FAIL: parse-error-token (got [$ERR])"; F=$((F+1));; esac
ck parse-error-silent "" "$(printf 'not json' | python3 "$PY" --fields TRUSTEE --error-token '')"

# 5) empty uid set -> no matches (empty tenant, no users)
ck empty-set "" "$(printf '%s' "$J" | python3 "$PY" --fields ID --trustor-in '')"

# 6) bad --fields -> exit 2
printf '%s' "$J" | python3 "$PY" --fields ZZZ >/dev/null 2>&1; ck bad-fields-rc 2 $?

echo "RESULT: PASS=$P FAIL=$F"
[ "$F" = 0 ] && echo "ALL PASS" || { echo "FAILURES"; exit 1; }
