#!/bin/bash

echo "=== Debugging 403 Error ==="
echo ""

# Rebuild the app
echo "1. Rebuilding application..."
mvn clean package -DskipTests

if [ $? -ne 0 ]; then
    echo "Build failed!"
    exit 1
fi

# Stop and remove the app container
echo ""
echo "2. Stopping app container..."
docker-compose stop app
docker-compose rm -f app

# Start the app container
echo ""
echo "3. Starting app container..."
docker-compose up -d app

# Wait for app to start
echo ""
echo "4. Waiting for app to start (30 seconds)..."
sleep 30

# Check app logs for JWT converter debug output
echo ""
echo "5. Checking app logs..."
docker-compose logs app | tail -50

# Get a fresh token
echo ""
echo "6. Getting fresh 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 "username=superadmin" \
  -d "password=admin123" \
  -d "grant_type=password" \
  -d "client_id=b2b-flight-backend" \
  -d "client_secret=b2b-flight-backend-secret" | jq -r '.access_token')

if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
    echo "Failed to get token!"
    exit 1
fi

echo "Token obtained successfully"

# Test the endpoint
echo ""
echo "7. Testing GET /api/v1/agencies endpoint..."
curl -v -X GET "http://localhost:8081/api/v1/agencies" \
  -H "accept: */*" \
  -H "Authorization: Bearer $TOKEN"

echo ""
echo ""
echo "8. Check app logs again for JWT converter debug output..."
docker-compose logs app | tail -100

echo ""
echo "=== Debug Complete ==="
