#!/bin/bash

echo "Fixing backend client configuration..."

# Get admin token
ADMIN_TOKEN=$(curl -s -X POST "http://localhost:8080/realms/master/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "username=admin" \
  -d "password=admin" \
  -d "grant_type=password" \
  -d "client_id=admin-cli" | jq -r '.access_token')

echo "Got admin token"

# Get backend client ID
CLIENT_UUID=$(curl -s -X GET "http://localhost:8080/admin/realms/b2b-flight-platform/clients" \
  -H "Authorization: Bearer $ADMIN_TOKEN" | jq -r '.[] | select(.clientId=="b2b-flight-backend") | .id')

echo "Backend client UUID: $CLIENT_UUID"

# Update client configuration
curl -s -X PUT "http://localhost:8080/admin/realms/b2b-flight-platform/clients/$CLIENT_UUID" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "b2b-flight-backend",
    "enabled": true,
    "clientAuthenticatorType": "client-secret",
    "secret": "b2b-flight-backend-secret",
    "directAccessGrantsEnabled": true,
    "serviceAccountsEnabled": true,
    "standardFlowEnabled": true,
    "implicitFlowEnabled": false,
    "publicClient": false,
    "protocol": "openid-connect",
    "attributes": {
      "access.token.lifespan": "3600"
    }
  }'

echo ""
echo "✅ Backend client updated"
echo ""
echo "Now testing login with frontend client (public)..."

# Test with frontend client (public, no secret needed)
RESPONSE=$(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-frontend" \
  -d "grant_type=password" \
  -d "username=superadmin" \
  -d "password=SuperAdmin123!")

if echo "$RESPONSE" | jq -e '.access_token' > /dev/null 2>&1; then
  echo "✅ Frontend client login works!"
  echo ""
  echo "Access token received. Now you can login from the Angular app."
  echo ""
  echo "Credentials:"
  echo "  Username: superadmin"
  echo "  Password: SuperAdmin123!"
  echo ""
  echo "Go to http://localhost:4200 and try logging in!"
else
  echo "❌ Login failed:"
  echo "$RESPONSE" | jq '.'
fi
