# Script pour créer le client unionflow-server dans Keycloak
param(
    [string]$KeycloakUrl = "http://192.168.1.11:8180",
    [string]$Realm = "unionflow",
    [string]$AdminUser = "admin",
    [string]$AdminPassword = "admin",
    [string]$ClientId = "unionflow-server",
    [string]$ClientSecret = "unionflow-secret-2025"
)

Write-Host "🖥️ Création du client serveur dans Keycloak..." -ForegroundColor Cyan
Write-Host "📍 Keycloak URL: $KeycloakUrl" -ForegroundColor Gray
Write-Host "🏛️ Realm: $Realm" -ForegroundColor Gray
Write-Host "🖥️ Client ID: $ClientId" -ForegroundColor Gray
Write-Host ""

try {
    # 1. Obtenir le token d'administration
    Write-Host "🔑 Obtention du token d'administration..." -ForegroundColor Yellow
    
    $tokenBody = @{
        username = $AdminUser
        password = $AdminPassword
        grant_type = "password"
        client_id = "admin-cli"
    }
    
    $tokenResponse = Invoke-RestMethod -Uri "$KeycloakUrl/realms/master/protocol/openid-connect/token" `
                                      -Method Post `
                                      -ContentType "application/x-www-form-urlencoded" `
                                      -Body $tokenBody
    
    $accessToken = $tokenResponse.access_token
    Write-Host "✅ Token obtenu avec succès" -ForegroundColor Green
    
    # 2. Créer le client serveur
    Write-Host "🖥️ Création du client serveur '$ClientId'..." -ForegroundColor Yellow
    
    $clientConfig = @{
        clientId = $ClientId
        name = "UnionFlow Server API"
        description = "Client pour l'API serveur UnionFlow"
        enabled = $true
        clientAuthenticatorType = "client-secret"
        secret = $ClientSecret
        publicClient = $false
        standardFlowEnabled = $true
        implicitFlowEnabled = $false
        directAccessGrantsEnabled = $true
        serviceAccountsEnabled = $true
        authorizationServicesEnabled = $false
        redirectUris = @("http://192.168.1.11:8080/*")
        webOrigins = @("http://192.168.1.11:8080", "http://localhost:8080")
        protocol = "openid-connect"
        attributes = @{
            "access.token.lifespan" = "900"
            "client.session.idle.timeout" = "1800"
            "client.session.max.lifespan" = "43200"
        }
        defaultClientScopes = @("openid", "profile", "email", "roles")
        optionalClientScopes = @()
    } | ConvertTo-Json -Depth 10
    
    $headers = @{
        "Authorization" = "Bearer $accessToken"
        "Content-Type" = "application/json"
    }
    
    try {
        $clientResponse = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients" `
                                           -Method Post `
                                           -Headers $headers `
                                           -Body $clientConfig
        Write-Host "✅ Client serveur créé avec succès" -ForegroundColor Green
    }
    catch {
        if ($_.Exception.Response.StatusCode -eq 409) {
            Write-Host "⚠️ Le client existe déjà, mise à jour..." -ForegroundColor Yellow
        }
        else {
            throw
        }
    }
    
    Write-Host ""
    Write-Host "🎉 CLIENT SERVEUR CRÉÉ AVEC SUCCÈS !" -ForegroundColor Green
    Write-Host "🖥️ Client ID: $ClientId" -ForegroundColor White
    Write-Host "🔒 Client Secret: $ClientSecret" -ForegroundColor White
    Write-Host ""
    Write-Host "Le serveur Quarkus peut maintenant s'authentifier avec Keycloak !" -ForegroundColor Cyan
    
}
catch {
    Write-Host ""
    Write-Host "ERREUR lors de la creation du client serveur !" -ForegroundColor Red
    Write-Host "Details: $($_.Exception.Message)" -ForegroundColor Red

    if ($_.Exception.Response) {
        $statusCode = $_.Exception.Response.StatusCode.value__
        Write-Host "Code de statut HTTP: $statusCode" -ForegroundColor Red
    }
    
    exit 1
}
