#!/bin/bash
# Sanity: merchant global + demo instance delays are demo-short (pay/refund/wire).
# Run on koopa (network to :9010 / public merchant).
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=lib.sh
source "$ROOT/lib.sh"

# Expected upper bounds (seconds) — fail if longer (package defaults 1d/15d/1w)
MAX_PAY_S=${MAX_PAY_S:-120}
MAX_REFUND_S=${MAX_REFUND_S:-120}
MAX_WIRE_S=${MAX_WIRE_S:-120}

echo "=== Merchant delay defaults (expect short demo values) ==="

tmp=$(mktemp)
curl -sk -m 12 -o "$tmp" "${MERCHANT_PUBLIC}/config" || curl -sk -m 12 -o "$tmp" "${MERCHANT_URL}/config"
python3 - "$tmp" "$MAX_PAY_S" "$MAX_REFUND_S" "$MAX_WIRE_S" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
max_pay, max_ref, max_wire = map(float, sys.argv[2:5])
fails=0
for key, mx in (
  ("default_pay_delay", max_pay),
  ("default_refund_delay", max_ref),
  ("default_wire_transfer_delay", max_wire),
):
  us=d.get(key,{}).get("d_us")
  s=(us or 0)/1e6
  ok = us is not None and s <= mx
  print(f"{'OK' if ok else 'FAIL'}  {key}: {s:.0f}s (max {mx:.0f}s)")
  if not ok: fails+=1
print("currency", d.get("currency"))
sys.exit(fails)
PY
ec=$?
rm -f "$tmp"
FAILS=$((FAILS + ec))

# Instance goa-demo if password present
if [ -f /root/merchant-goa-demo-cp4zqk-password.txt ]; then
  MPW=$(tr -d '\n' </root/merchant-goa-demo-cp4zqk-password.txt)
  tmp=$(mktemp)
  curl -sk -m 12 -H "Authorization: Bearer secret-token:${MPW}" \
    -o "$tmp" "${MERCHANT_URL}/instances/goa-demo-cp4zqk/private/" || true
  if [ -s "$tmp" ]; then
    python3 - "$tmp" "$MAX_PAY_S" "$MAX_REFUND_S" "$MAX_WIRE_S" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
max_pay, max_ref, max_wire = map(float, sys.argv[2:5])
fails=0
for key, mx in (
  ("default_pay_delay", max_pay),
  ("default_refund_delay", max_ref),
  ("default_wire_transfer_delay", max_wire),
):
  us=d.get(key,{}).get("d_us")
  s=(us or 0)/1e6
  ok = us is not None and s <= mx
  print(f"{'OK' if ok else 'FAIL'}  instance {key}: {s:.0f}s")
  if not ok: fails+=1
sys.exit(fails)
PY
    FAILS=$((FAILS + $?))
  else
    warn "could not load instance goa-demo-cp4zqk"
  fi
  rm -f "$tmp"
fi

echo "=== summary fails=$FAILS ==="
exit "$FAILS"
