#!/usr/bin/env bash
# Offline fixture tests for bank-match.sh — no credentials, no network, no writes.
# Proves the PASS 0 tx-id normalization (varchar(50) canonical short form):
#   1. txid-normalize — a long Qonto feed id (~67 chars) matches a règlement whose
#      num was stored SHORT (UUID suffix, what payment-record.sh stores) AND one
#      stored LONG (historical); a Wise numeric id matches unchanged. Every pair
#      is ~19 days apart — far outside the ±7d window — so only the id-based
#      PASS 0 can pair them. Expect exit 0, 3 × [tx-id].
#   2. txid-no-num — same bank movement but the payment has num="" → must NOT
#      match (the id is proof; its absence isn't). Expect exit 1, 0 matched.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BM="${SCRIPT_DIR}/../scripts/bank-match.sh"

fail() { echo "FAIL: $*" >&2; exit 1; }
count() { grep -c "$1" <<<"$2" || true; }

bash -n "${BM}" || fail "bash -n bank-match.sh"

# --- Case 1: long-Qonto-id ↔ short-num (+ long-num back-compat + Wise) ---
OUT="$(bash "${BM}" --fixtures "${SCRIPT_DIR}/fixtures/txid-normalize" \
        --since 2026-06-01 --until 2026-06-30)" \
  || fail "txid-normalize: expected exit 0, got $?"
[[ "$(count '↔\[tx-id\]' "${OUT}")" == 3 ]] || fail "txid-normalize: expected 3 [tx-id] matches
${OUT}"
grep -q 'FS-OVH-2606' <<<"${OUT}" || fail "txid-normalize: long feed id ↔ SHORT num (the varchar(50) form) did not match"
grep -q 'FS-SCW-2606' <<<"${OUT}" || fail "txid-normalize: long feed id ↔ LONG num (historical form) did not match"
grep -q 'FAC003-CL0001003' <<<"${OUT}" || fail "txid-normalize: Wise numeric id match broken"
grep -q '# 3 matched, 0 internal, 0 avoir-netted, 0 bank-known, 0 bank-UNKNOWN, 0 dol-only-API' <<<"${OUT}" \
  || fail "txid-normalize: unexpected bucket counts
${OUT}"

# --- Case 2: payment without num must not tx-id-match ---
rc=0
OUT2="$(bash "${BM}" --fixtures "${SCRIPT_DIR}/fixtures/txid-no-num" \
         --since 2026-06-01 --until 2026-06-30)" || rc=$?
[[ "${rc}" == 1 ]] || fail "txid-no-num: expected exit 1, got ${rc}"
grep -q '# 0 matched' <<<"${OUT2}" || fail "txid-no-num: nothing should match
${OUT2}"
[[ "$(count '↔\[tx-id\]' "${OUT2}")" == 0 ]] || fail "txid-no-num: empty num must not produce a [tx-id] match"

echo "OK: bank-match fixture tests passed (3 tx-id matches incl. long↔short + long↔long + Wise; empty-num negative)"
