#!/bin/bash
# Debug Authentication

echo "🔍 Debugging Authentication"
echo "==========================="
echo ""

# Get token
TOKEN=$(curl -s -X POST 'http://localhost:8080/realms/b2b-flight-platform/protocol/openid-connect/token' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'client_id=b2b-flight-backend' \
  -d 'client_secret=b2b-flight-backend-secret' \
  -d 'username=superadmin' \
  -d 'password=admin123' \
  -d 'grant_type=password' | jq -r '.access_token')

echo "1. Token roles from Keycloak:"
PAYLOAD=$(echo $TOKEN | cut -d'.' -f2)
PADDED=$(printf '%s' "$PAYLOAD" | sed 's/-/+/g; s/_/\//g')
echo "$PADDED===" | base64 -d 2>/dev/null | jq -r '.realm_access.roles[]'
echo ""

echo "2. Testing endpoint with token..."
curl -v -X GET 'http://localhost:8081/api/v1/agencies' \
  -H "Authorization: Bearer $TOKEN" 2>&1 | grep -E "< HTTP|WWW-Authenticate"
echo ""

echo "3. Check app logs for authentication details:"
echo "   docker-compose logs app --tail=20"
