# Script de configuration du client Keycloak pour Lions User Manager
# Usage: .\setup-keycloak-client.ps1

Write-Host "=============================================" -ForegroundColor Cyan
Write-Host "Configuration Client Keycloak" -ForegroundColor Cyan
Write-Host "=============================================" -ForegroundColor Cyan
Write-Host ""

# Configuration
$keycloakUrl = "http://localhost:8180"
$realm = "lions-user-manager"
$clientId = "lions-user-manager-client"
$clientSecret = "NTuaQpk5E6qiMqAWTFrCOcIkOABzZzKO"
$redirectUri = "http://localhost:8082/*"

# Étape 1 : Vérifier Keycloak
Write-Host "[1/5] Vérification de Keycloak..." -ForegroundColor Yellow
try {
    $response = Invoke-WebRequest -Uri "$keycloakUrl" -Method GET -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop
    Write-Host "   ✅ Keycloak accessible" -ForegroundColor Green
} catch {
    Write-Host "   ❌ Keycloak inaccessible sur $keycloakUrl" -ForegroundColor Red
    Write-Host "   Démarrez Keycloak avant de continuer" -ForegroundColor Yellow
    exit 1
}

# Étape 2 : Obtenir un token admin
Write-Host "[2/5] Authentification admin..." -ForegroundColor Yellow
try {
    $tokenParams = @{
        Uri = "$keycloakUrl/realms/master/protocol/openid-connect/token"
        Method = "POST"
        Body = @{
            client_id = "admin-cli"
            grant_type = "password"
            username = "admin"
            password = "admin"
        }
        ContentType = "application/x-www-form-urlencoded"
    }
    $tokenResponse = Invoke-RestMethod @tokenParams
    $adminToken = $tokenResponse.access_token
    Write-Host "   ✅ Token admin obtenu" -ForegroundColor Green
} catch {
    Write-Host "   ❌ Échec authentification admin" -ForegroundColor Red
    Write-Host "   Vérifiez les identifiants admin/admin" -ForegroundColor Yellow
    exit 1
}

# Étape 3 : Vérifier si le realm existe
Write-Host "[3/5] Vérification du realm '$realm'..." -ForegroundColor Yellow
try {
    $headers = @{
        Authorization = "Bearer $adminToken"
        Accept = "application/json"
    }
    $realmResponse = Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm" -Headers $headers -Method GET -ErrorAction Stop
    Write-Host "   ✅ Realm '$realm' existe" -ForegroundColor Green
} catch {
    if ($_.Exception.Response.StatusCode -eq 404) {
        Write-Host "   ⚠️  Realm '$realm' n'existe pas" -ForegroundColor Yellow
        Write-Host "   Créez le realm manuellement via la console Keycloak:" -ForegroundColor Yellow
        Write-Host "   1. Accédez à $keycloakUrl" -ForegroundColor Gray
        Write-Host "   2. Administration Console > Create Realm" -ForegroundColor Gray
        Write-Host "   3. Realm name: $realm" -ForegroundColor Gray
        exit 1
    }
    Write-Host "   ❌ Erreur vérification realm: $_" -ForegroundColor Red
    exit 1
}

# Étape 4 : Vérifier si le client existe
Write-Host "[4/5] Vérification du client '$clientId'..." -ForegroundColor Yellow
try {
    $clientsResponse = Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients?clientId=$clientId" -Headers $headers -Method GET

    if ($clientsResponse.Count -eq 0) {
        Write-Host "   ⚠️  Client '$clientId' n'existe pas" -ForegroundColor Yellow
        Write-Host "   Création du client..." -ForegroundColor Yellow

        # Créer le client
        $clientData = @{
            clientId = $clientId
            enabled = $true
            protocol = "openid-connect"
            publicClient = $false
            standardFlowEnabled = $true
            directAccessGrantsEnabled = $true
            serviceAccountsEnabled = $false
            implicitFlowEnabled = $false
            redirectUris = @($redirectUri, "http://localhost:8082/auth/callback")
            webOrigins = @("http://localhost:8082")
            attributes = @{
                "pkce.code.challenge.method" = "S256"
            }
            secret = $clientSecret
        } | ConvertTo-Json -Depth 10

        $createHeaders = @{
            Authorization = "Bearer $adminToken"
            "Content-Type" = "application/json"
        }

        Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients" -Headers $createHeaders -Method POST -Body $clientData
        Write-Host "   ✅ Client créé avec succès" -ForegroundColor Green

        # Récupérer l'ID du client nouvellement créé
        Start-Sleep -Seconds 1
        $clientsResponse = Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients?clientId=$clientId" -Headers $headers -Method GET
        $client = $clientsResponse[0]

        # Configurer le secret
        $secretData = @{
            type = "secret"
            value = $clientSecret
        } | ConvertTo-Json

        Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients/$($client.id)/client-secret" -Headers $createHeaders -Method POST -Body $secretData
        Write-Host "   ✅ Secret configuré" -ForegroundColor Green
    } else {
        Write-Host "   ✅ Client '$clientId' existe déjà" -ForegroundColor Green
        $client = $clientsResponse[0]

        # Vérifier les redirect URIs
        Write-Host "   Vérification des redirect URIs..." -ForegroundColor Gray
        $clientDetails = Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients/$($client.id)" -Headers $headers -Method GET

        if ($clientDetails.redirectUris -notcontains $redirectUri) {
            Write-Host "   ⚠️  Redirect URI manquant, mise à jour..." -ForegroundColor Yellow
            $clientDetails.redirectUris += $redirectUri
            $clientDetails.redirectUris += "http://localhost:8082/auth/callback"

            $updateData = $clientDetails | ConvertTo-Json -Depth 10
            $updateHeaders = @{
                Authorization = "Bearer $adminToken"
                "Content-Type" = "application/json"
            }
            Invoke-RestMethod -Uri "$keycloakUrl/admin/realms/$realm/clients/$($client.id)" -Headers $updateHeaders -Method PUT -Body $updateData
            Write-Host "   ✅ Redirect URIs mis à jour" -ForegroundColor Green
        }
    }
} catch {
    Write-Host "   ❌ Erreur configuration client: $_" -ForegroundColor Red
    Write-Host "   $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# Étape 5 : Résumé
Write-Host ""
Write-Host "[5/5] Configuration terminée" -ForegroundColor Yellow
Write-Host ""
Write-Host "=============================================" -ForegroundColor Cyan
Write-Host "Résumé de la Configuration" -ForegroundColor Cyan
Write-Host "=============================================" -ForegroundColor Cyan
Write-Host "Realm:        $realm" -ForegroundColor White
Write-Host "Client ID:    $clientId" -ForegroundColor White
Write-Host "Client Secret: $clientSecret" -ForegroundColor White
Write-Host "Redirect URI: $redirectUri" -ForegroundColor White
Write-Host ""
Write-Host "✅ Le client est configuré et prêt" -ForegroundColor Green
Write-Host ""
Write-Host "Prochaines étapes:" -ForegroundColor Cyan
Write-Host "1. Redémarrez le client JSF si nécessaire (Ctrl+C puis mvn quarkus:dev)" -ForegroundColor Gray
Write-Host "2. Supprimez les cookies du navigateur pour localhost:8082" -ForegroundColor Gray
Write-Host "3. Accédez à http://localhost:8082" -ForegroundColor Gray
Write-Host ""
