#!/bin/bash

# Script pour corriger la configuration du client Keycloak
echo "🔧 Correction de la configuration du client Keycloak"

# Variables
KEYCLOAK_URL="http://localhost:8180"
REALM_NAME="unionflow"
CLIENT_ID="unionflow-server"
ADMIN_TOKEN="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhYkxDejZoZ1dEdmU4T3E2UzlxNVduMEF5RkFSZmV6MVlzRm44T05mdkNRIn0.eyJleHAiOjE3NTc4MjQyODUsImlhdCI6MTc1NzgyNDIyNSwianRpIjoib25sdHJvOmJiYTYzMDc4LWUwZjAtMGYwYS0wOWZiLTIwNDY4NGQyZTJmYSIsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODE4MC9yZWFsbXMvbWFzdGVyIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYWRtaW4tY2xpIiwic2lkIjoiNzQ2NjA2MjEtNjNiZC00OTcyLThlOWYtZjY3NDQ2YWM5MzRlIiwic2NvcGUiOiJlbWFpbCBwcm9maWxlIn0.AuYvEHCYv5qXG1vhkae3fESY4y2-RMJSyuIvOXvHmALIntinDDNZPvjIdhcIxf3VyaoBE02IuavjcLs8q-yqUPR7iHzeq6SSXv8ic_lDjH_fosKpiL6D4Rz4I6V6dDS41aZrKOBA7iyucEeVc5EtJ29NFtWDZmty5WsV2_onPBlLKY8Rcih33dvWop0BKGwKS--ys6pdEPgkIVaxZRSyJ2y61inp55QPvYEPIR9epu656VrNb6c7yNfDzbQbmnj0SsIhHYw4bFnj0VOjivhFXDwxkIUHvjzqgtY_Ozh5-UxbblHgj_elua8VyIw22CZP7mrf_MsxTnjG7tb-qyR-cw"

# Récupérer l'ID du client
echo "🔍 Recherche du client '$CLIENT_ID'..."
CLIENT_DATA=$(curl -s -X GET "$KEYCLOAK_URL/admin/realms/$REALM_NAME/clients?clientId=$CLIENT_ID" \
    -H "Authorization: Bearer $ADMIN_TOKEN")

CLIENT_UUID=$(echo $CLIENT_DATA | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)

if [ -z "$CLIENT_UUID" ]; then
    echo "❌ Client non trouvé"
    exit 1
fi

echo "✅ Client trouvé: $CLIENT_UUID"

# Mettre à jour la configuration du client
echo "🔧 Mise à jour de la configuration du client..."

CLIENT_UPDATE='{
    "directAccessGrantsEnabled": true,
    "publicClient": false,
    "serviceAccountsEnabled": true,
    "standardFlowEnabled": true,
    "implicitFlowEnabled": false,
    "authorizationServicesEnabled": false,
    "secret": "unionflow-secret-2025"
}'

RESPONSE=$(curl -s -X PUT "$KEYCLOAK_URL/admin/realms/$REALM_NAME/clients/$CLIENT_UUID" \
    -H "Authorization: Bearer $ADMIN_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$CLIENT_UPDATE" \
    -w "%{http_code}")

if [[ "$RESPONSE" == *"204"* ]]; then
    echo "✅ Configuration du client mise à jour"
    
    # Test d'authentification
    echo ""
    echo "🧪 Test d'authentification avec testuser..."
    AUTH_RESPONSE=$(curl -s -X POST "$KEYCLOAK_URL/realms/$REALM_NAME/protocol/openid-connect/token" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "username=testuser&password=test123&grant_type=password&client_id=$CLIENT_ID&client_secret=unionflow-secret-2025")
    
    AUTH_TOKEN=$(echo $AUTH_RESPONSE | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
    
    if [ -n "$AUTH_TOKEN" ]; then
        echo "✅ Authentification réussie !"
        echo "🔑 Token obtenu (tronqué): ${AUTH_TOKEN:0:50}..."
        
        # Test d'accès à l'API UnionFlow
        echo ""
        echo "🧪 Test d'accès à l'API UnionFlow..."
        API_RESPONSE=$(curl -s -w "%{http_code}" -H "Authorization: Bearer $AUTH_TOKEN" "http://localhost:8080/api/organisations")
        HTTP_CODE=$(echo "$API_RESPONSE" | tail -c 4)
        BODY=$(echo "$API_RESPONSE" | head -c -4)
        
        echo "📋 Code de réponse: $HTTP_CODE"
        
        if [ "$HTTP_CODE" = "200" ]; then
            echo "✅ Accès API réussi !"
            echo "📋 Réponse: ${BODY:0:200}..."
        elif [ "$HTTP_CODE" = "403" ]; then
            echo "⚠️ Accès refusé - Permissions insuffisantes"
        elif [ "$HTTP_CODE" = "401" ]; then
            echo "⚠️ Non autorisé - Token invalide"
        else
            echo "⚠️ Réponse inattendue (Code: $HTTP_CODE)"
            echo "📋 Réponse: $BODY"
        fi
        
        # Test du health check
        echo ""
        echo "🧪 Test du health check..."
        HEALTH_RESPONSE=$(curl -s "http://localhost:8080/health")
        echo "✅ Health check: $HEALTH_RESPONSE"
        
        # Test de Swagger UI
        echo ""
        echo "🧪 Test de Swagger UI..."
        SWAGGER_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8080/q/swagger-ui")
        if [ "$SWAGGER_CODE" = "200" ]; then
            echo "✅ Swagger UI accessible"
        else
            echo "⚠️ Swagger UI non accessible (Code: $SWAGGER_CODE)"
        fi
        
        echo ""
        echo "🎉 Configuration Keycloak terminée avec succès !"
        echo "======================================="
        echo "✅ Keycloak configuré et fonctionnel"
        echo "✅ UnionFlow Server intégré avec Keycloak"
        echo "✅ Authentification JWT fonctionnelle"
        echo "✅ API protégée correctement"
        echo ""
        echo "🔗 URLs importantes:"
        echo "   • UnionFlow API: http://localhost:8080"
        echo "   • Swagger UI: http://localhost:8080/q/swagger-ui"
        echo "   • Health Check: http://localhost:8080/health"
        echo "   • Keycloak Admin: http://localhost:8180/admin"
        echo ""
        echo "👤 Utilisateur de test:"
        echo "   • Username: testuser"
        echo "   • Password: test123"
        
    else
        echo "❌ Échec de l'authentification"
        echo "Réponse: $AUTH_RESPONSE"
    fi
else
    echo "❌ Échec de la mise à jour du client"
    echo "Réponse: $RESPONSE"
fi
