# Script de vérification de la configuration Keycloak
# Pour Lions User Manager

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  Vérification Configuration Keycloak" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""

$KEYCLOAK_URL = "http://localhost:8180"
$ADMIN_USER = "admin"
$ADMIN_PASS = "admin"

Write-Host "1. Connexion à Keycloak Master..." -ForegroundColor Yellow

# Obtenir le token admin
try {
    $tokenResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" `
        -Method Post `
        -ContentType "application/x-www-form-urlencoded" `
        -Body @{
            grant_type = "password"
            client_id = "admin-cli"
            username = $ADMIN_USER
            password = $ADMIN_PASS
        }

    $ACCESS_TOKEN = $tokenResponse.access_token
    Write-Host "   ✅ Connexion réussie au realm master" -ForegroundColor Green
} catch {
    Write-Host "   ❌ Échec de connexion au realm master!" -ForegroundColor Red
    Write-Host "   Erreur: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "2. Vérification du realm 'lions-user-manager'..." -ForegroundColor Yellow

# Vérifier si le realm existe
try {
    $realm = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/lions-user-manager" `
        -Method Get `
        -Headers @{
            Authorization = "Bearer $ACCESS_TOKEN"
        }
    Write-Host "   ✅ Realm 'lions-user-manager' existe" -ForegroundColor Green
    Write-Host "      Enabled: $($realm.enabled)" -ForegroundColor Gray
} catch {
    Write-Host "   ❌ Realm 'lions-user-manager' n'existe PAS!" -ForegroundColor Red
    Write-Host "   Vous devez créer ce realm dans Keycloak" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "3. Vérification du client 'lions-user-manager-client'..." -ForegroundColor Yellow

# Récupérer les clients du realm
try {
    $clients = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/lions-user-manager/clients" `
        -Method Get `
        -Headers @{
            Authorization = "Bearer $ACCESS_TOKEN"
        }

    $client = $clients | Where-Object { $_.clientId -eq "lions-user-manager-client" }

    if ($client) {
        Write-Host "   ✅ Client 'lions-user-manager-client' existe" -ForegroundColor Green
        Write-Host "      Client ID: $($client.clientId)" -ForegroundColor Gray
        Write-Host "      Enabled: $($client.enabled)" -ForegroundColor Gray
        Write-Host "      Public Client: $($client.publicClient)" -ForegroundColor Gray
        Write-Host "      Standard Flow Enabled: $($client.standardFlowEnabled)" -ForegroundColor Gray
        Write-Host "      Redirect URIs: $($client.redirectUris -join ', ')" -ForegroundColor Gray

        if (-not $client.enabled) {
            Write-Host "   ⚠️  ATTENTION: Le client est désactivé!" -ForegroundColor Red
        }

        if ($client.publicClient) {
            Write-Host "   ⚠️  ATTENTION: Le client est PUBLIC (devrait être CONFIDENTIAL)" -ForegroundColor Yellow
        }
    } else {
        Write-Host "   ❌ Client 'lions-user-manager-client' N'EXISTE PAS!" -ForegroundColor Red
        Write-Host "   VOUS DEVEZ LE CRÉER DANS KEYCLOAK!" -ForegroundColor Red
        Write-Host ""
        Write-Host "   Configuration requise:" -ForegroundColor Yellow
        Write-Host "   - Client ID: lions-user-manager-client" -ForegroundColor Gray
        Write-Host "   - Client Protocol: openid-connect" -ForegroundColor Gray
        Write-Host "   - Access Type: confidential" -ForegroundColor Gray
        Write-Host "   - Standard Flow: ON" -ForegroundColor Gray
        Write-Host "   - Valid Redirect URIs: http://localhost:8080/*" -ForegroundColor Gray
        Write-Host "   - Web Origins: http://localhost:8080" -ForegroundColor Gray
        exit 1
    }
} catch {
    Write-Host "   ❌ Erreur lors de la récupération des clients" -ForegroundColor Red
    Write-Host "   Erreur: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "4. Vérification des rôles du realm..." -ForegroundColor Yellow

try {
    $roles = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/lions-user-manager/roles" `
        -Method Get `
        -Headers @{
            Authorization = "Bearer $ACCESS_TOKEN"
        }

    Write-Host "   ✅ $($roles.Count) rôles trouvés" -ForegroundColor Green

    $roles | ForEach-Object {
        Write-Host "      - $($_.name)" -ForegroundColor Gray
    }
} catch {
    Write-Host "   ⚠️  Impossible de récupérer les rôles" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "5. Vérification des utilisateurs..." -ForegroundColor Yellow

try {
    $users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/lions-user-manager/users?max=5" `
        -Method Get `
        -Headers @{
            Authorization = "Bearer $ACCESS_TOKEN"
        }

    Write-Host "   ✅ $($users.Count) utilisateur(s) trouvé(s) (max 5 affichés)" -ForegroundColor Green

    $users | ForEach-Object {
        Write-Host "      - $($_.username) ($($_.email))" -ForegroundColor Gray
    }

    if ($users.Count -eq 0) {
        Write-Host "   ⚠️  Aucun utilisateur dans le realm" -ForegroundColor Yellow
        Write-Host "   Créez des utilisateurs pour tester l'application" -ForegroundColor Yellow
    }
} catch {
    Write-Host "   ⚠️  Impossible de récupérer les utilisateurs" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  Résumé de la Configuration" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "CLIENT (Pour l'authentification des utilisateurs):" -ForegroundColor Yellow
Write-Host "  Realm: lions-user-manager" -ForegroundColor Gray
Write-Host "  Client ID: lions-user-manager-client" -ForegroundColor Gray
Write-Host "  URL: $KEYCLOAK_URL/realms/lions-user-manager" -ForegroundColor Gray
Write-Host ""
Write-Host "SERVER ADMIN (Pour administrer tous les realms):" -ForegroundColor Yellow
Write-Host "  Realm: master" -ForegroundColor Gray
Write-Host "  Client ID: admin-cli" -ForegroundColor Gray
Write-Host "  Username: admin" -ForegroundColor Gray
Write-Host "  URL: $KEYCLOAK_URL/realms/master" -ForegroundColor Gray
Write-Host ""
Write-Host "✅ Vérification terminée!" -ForegroundColor Green
