#!/bin/bash
# Smoke test for role routing and tenant isolation against a running, seeded instance.
#   BASE_URL=http://localhost:3000 SUPERADMIN_EMAIL=... SUPERADMIN_PASSWORD=... DEMO_PASSWORD=... bash scripts/smoke-auth.sh
# Requires the demo seed (SEED_DEMO_DATA=true). Exits non-zero on the first failed expectation.
set -u
B=${BASE_URL:-http://localhost:3000}
fail=0
login() { # email password jar
  rm -f "$3"
  local csrf; csrf=$(curl -s -c "$3" -b "$3" "$B/api/auth/csrf" | python3 -c "import sys,json;print(json.load(sys.stdin)['csrfToken'])")
  curl -s -o /dev/null -c "$3" -b "$3" -X POST "$B/api/auth/callback/credentials" \
    --data-urlencode "csrfToken=$csrf" --data-urlencode "email=$1" --data-urlencode "password=$2" --data-urlencode "redirectTo=/dashboard"
}
expect_redirect() { # label jar path expected-location-suffix ("" = expect 200)
  local out; out=$(curl -s -o /dev/null -w "%{http_code} %{redirect_url}" -b "$2" "$B$3")
  if [ -z "$4" ]; then [[ "$out" == 200* ]] || { echo "FAIL $1: $3 -> $out (wanted 200)"; fail=1; }
  else [[ "$out" == 307*"$4" ]] || { echo "FAIL $1: $3 -> $out (wanted redirect to $4)"; fail=1; }; fi
}
login "$SUPERADMIN_EMAIL" "$SUPERADMIN_PASSWORD" /tmp/sm_root
login admin@acme-expo.demo "$DEMO_PASSWORD" /tmp/sm_admin
login editor@acme-expo.demo "$DEMO_PASSWORD" /tmp/sm_editor
login maintenance@acme-expo.demo "$DEMO_PASSWORD" /tmp/sm_maint
login admin@northwind-events.demo "$DEMO_PASSWORD" /tmp/sm_nw

expect_redirect superadmin /tmp/sm_root /dashboard/super-admin ""
expect_redirect admin /tmp/sm_admin /dashboard/super-admin /dashboard/admin
expect_redirect editor /tmp/sm_editor /dashboard/admin /dashboard/editor
expect_redirect editor /tmp/sm_editor /dashboard/maintenance /dashboard/editor
expect_redirect maint /tmp/sm_maint /dashboard/editor /dashboard/maintenance
expect_redirect maint /tmp/sm_maint /dashboard/admin/pages /dashboard/maintenance
expect_redirect anon /dev/null /dashboard "/login?callbackUrl=${B//:/%3A}%2Fdashboard"

# Tenant isolation: acme admin must never see Northwind data, and vice versa.
curl -s -b /tmp/sm_admin "$B/dashboard/admin/pages" | grep -q "Northwind Summit" && { echo "FAIL: acme admin sees Northwind pages"; fail=1; }
curl -s -b /tmp/sm_nw "$B/dashboard/admin/tickets" | grep -q "Acme Expo 2027" && { echo "FAIL: northwind admin sees Acme tickets"; fail=1; }
[ $fail -eq 0 ] && echo "smoke-auth: all checks passed" || exit 1
