#!/usr/bin/env bash
# End-to-end SSO smoke: account issues a JWT for vocab + Pamela,
# we POST it to vocab's /api/sso/exchange, expect 200 with a Sanctum token.
set -e
cd /var/www/html/account

echo "=== Issuing JWT (account-side) ==="
JWT=$(php artisan tinker --execute='
  $u = \App\Models\User::where("email","pamelaliusm@gmail.com")->firstOrFail();
  $app = \App\Models\ClientApp::where("slug","vocab")->firstOrFail();
  $svc = app(\App\Services\Sso\SsoTokenService::class);
  echo $svc->issueForApp($u, $app);
' 2>&1 | tail -1)
echo "JWT length: ${#JWT}"
echo "First 40 chars: ${JWT:0:40}…"
echo ""

echo "=== Exchanging at vocabapi /api/sso/exchange ==="
RESP=$(curl -s -X POST https://vocabapi.allgifted.com/api/sso/exchange \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d "{\"sso_token\":\"${JWT}\"}")
echo "Response:"
echo "$RESP" | head -c 600
echo ""
echo ""

echo "=== Decoded fields ==="
echo "$RESP" | php -r '$d=json_decode(stream_get_contents(STDIN),true);if(isset($d["token"])){echo "token_len: ".strlen($d["token"])."\n";echo "user.id: ".$d["user"]["id"]."\n";echo "user.email: ".$d["user"]["email"]."\n";echo "user.is_premium: ".($d["user"]["is_premium"]?"true":"false")."\n";echo "school.slug: ".$d["school"]["slug"]."\n";}else{echo "NO TOKEN — response was: ".json_encode($d)."\n";}'

echo ""
echo "=== Verify the Sanctum token works against /api/auth/me ==="
TOKEN=$(echo "$RESP" | php -r '$d=json_decode(stream_get_contents(STDIN),true);echo $d["token"]??"";')
if [ -n "$TOKEN" ]; then
  curl -s https://vocabapi.allgifted.com/api/auth/me \
    -H "Accept: application/json" \
    -H "Authorization: Bearer ${TOKEN}" | head -c 400
  echo ""
fi
