#!/bin/bash
# Get Access Token for B2B Flight Ticketing Platform

echo "🔑 Getting Access Token..."
echo ""

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')

if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
    echo "❌ Failed to get token"
    echo ""
    echo "Troubleshooting:"
    echo "1. Check if Keycloak is running:"
    echo "   docker-compose ps keycloak"
    echo ""
    echo "2. Check if realm is configured:"
    echo "   ./keycloak/quick-setup.sh"
    exit 1
fi

echo "✅ Token obtained successfully!"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "YOUR ACCESS TOKEN:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "$TOKEN"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 How to use this token:"
echo ""
echo "1️⃣  In Swagger UI (http://localhost:8081/swagger-ui.html):"
echo "   • Click the 'Authorize' button (🔓 icon, top right)"
echo "   • In the 'Value' field, enter:"
echo "     Bearer $TOKEN"
echo "   • Click 'Authorize' then 'Close'"
echo "   • Now you can test any endpoint!"
echo ""
echo "2️⃣  In curl commands:"
echo "   curl -X GET 'http://localhost:8081/api/agencies' \\"
echo "     -H 'Authorization: Bearer $TOKEN'"
echo ""
echo "3️⃣  In Postman:"
echo "   • Go to Authorization tab"
echo "   • Type: Bearer Token"
echo "   • Token: $TOKEN"
echo ""
echo "⏰ Note: Token expires in ~5 minutes. Run this script again to get a new one."
echo ""
