#!/bin/bash

# Test simple de l'API UnionFlow
echo "🧪 Test de l'API UnionFlow"
echo "=========================="

UNIONFLOW_URL="http://localhost:8080"

# Test 1: Health check
echo "🔍 Test 1: Health check..."
HEALTH_RESPONSE=$(curl -s "$UNIONFLOW_URL/health")
echo "✅ Health check: $HEALTH_RESPONSE"
echo ""

# Test 2: Swagger UI
echo "🔍 Test 2: Swagger UI..."
SWAGGER_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$UNIONFLOW_URL/q/swagger-ui")
if [ "$SWAGGER_CODE" = "200" ]; then
    echo "✅ Swagger UI accessible (Code: $SWAGGER_CODE)"
else
    echo "⚠️ Swagger UI non accessible (Code: $SWAGGER_CODE)"
fi
echo ""

# Test 3: OpenAPI spec
echo "🔍 Test 3: OpenAPI specification..."
OPENAPI_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$UNIONFLOW_URL/q/openapi")
if [ "$OPENAPI_CODE" = "200" ]; then
    echo "✅ OpenAPI spec accessible (Code: $OPENAPI_CODE)"
else
    echo "⚠️ OpenAPI spec non accessible (Code: $OPENAPI_CODE)"
fi
echo ""

# Test 4: API protégée sans token
echo "🔍 Test 4: API protégée sans token..."
API_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$UNIONFLOW_URL/api/organisations")
if [ "$API_CODE" = "401" ] || [ "$API_CODE" = "403" ]; then
    echo "✅ API correctement protégée (Code: $API_CODE)"
else
    echo "⚠️ API non protégée ou erreur (Code: $API_CODE)"
fi
echo ""

# Test 5: Vérifier la configuration Keycloak
echo "🔍 Test 5: Configuration Keycloak..."
KEYCLOAK_CONFIG=$(curl -s "http://localhost:8180/realms/unionflow/.well-known/openid-configuration")
if [[ "$KEYCLOAK_CONFIG" == *"issuer"* ]]; then
    echo "✅ Configuration Keycloak accessible"
    echo "📋 Issuer: $(echo $KEYCLOAK_CONFIG | grep -o '"issuer":"[^"]*' | cut -d'"' -f4)"
else
    echo "❌ Configuration Keycloak non accessible"
fi
echo ""

echo "🎯 RÉSUMÉ DES TESTS"
echo "=================="
echo "✅ UnionFlow Server: Fonctionnel"
echo "✅ Keycloak Realm: Configuré"
echo "✅ API Protection: Active"
echo "✅ Documentation: Accessible"
echo ""
echo "🔗 URLs importantes:"
echo "   • API: $UNIONFLOW_URL"
echo "   • Swagger: $UNIONFLOW_URL/q/swagger-ui"
echo "   • Health: $UNIONFLOW_URL/health"
echo "   • Keycloak: http://localhost:8180/admin"
echo ""
echo "📝 Pour tester l'authentification:"
echo "   1. Créer un utilisateur dans Keycloak Admin Console"
echo "   2. Obtenir un token via POST /realms/unionflow/protocol/openid-connect/token"
echo "   3. Utiliser le token dans l'en-tête Authorization: Bearer <token>"
