# Script pour corriger la configuration du client mobile Keycloak
$KeycloakUrl = "http://192.168.1.11:8180"
$Realm = "unionflow"
$ClientId = "unionflow-mobile"

Write-Host "=== CORRECTION CONFIGURATION CLIENT MOBILE ===" -ForegroundColor Cyan
Write-Host ""

try {
    # 1. Obtenir token admin
    Write-Host "1. Obtention du token admin..." -ForegroundColor Yellow
    $tokenBody = "username=admin&password=admin&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" -ForegroundColor Green
    
    # 2. Récupérer le client existant
    Write-Host "2. Récupération du client '$ClientId'..." -ForegroundColor Yellow
    $headers = @{ "Authorization" = "Bearer $accessToken" }
    $clients = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients?clientId=$ClientId" -Method Get -Headers $headers
    
    if ($clients.Count -eq 0) {
        Write-Host "   ❌ Client non trouvé" -ForegroundColor Red
        exit 1
    }
    
    $client = $clients[0]
    $clientUuid = $client.id
    Write-Host "   ✅ Client trouvé: $clientUuid" -ForegroundColor Green
    
    # 3. Configuration correcte du client
    Write-Host "3. Mise à jour de la configuration..." -ForegroundColor Yellow
    
    $updatedClient = @{
        id = $clientUuid
        clientId = $ClientId
        name = "UnionFlow Mobile App"
        enabled = $true
        publicClient = $true
        standardFlowEnabled = $true
        implicitFlowEnabled = $false
        directAccessGrantsEnabled = $false
        serviceAccountsEnabled = $false
        authorizationServicesEnabled = $false
        rootUrl = "com.unionflow.mobile://"
        baseUrl = "com.unionflow.mobile://home"
        redirectUris = @(
            "com.unionflow.mobile://login-callback",
            "com.unionflow.mobile://login-callback/*",
            "com.unionflow.mobile://oauth/callback"
        )
        postLogoutRedirectUris = @(
            "com.unionflow.mobile://logout-callback",
            "com.unionflow.mobile://logout-callback/*"
        )
        webOrigins = @("+")
        attributes = @{
            "pkce.code.challenge.method" = "S256"
            "post.logout.redirect.uris" = "com.unionflow.mobile://logout-callback##com.unionflow.mobile://logout-callback/*"
            "access.token.lifespan" = "900"
            "client.session.idle.timeout" = "1800"
            "client.session.max.lifespan" = "43200"
        }
        defaultClientScopes = @("openid", "profile", "email", "roles")
        optionalClientScopes = @()
    } | ConvertTo-Json -Depth 10
    
    # 4. Appliquer la mise à jour
    Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$clientUuid" -Method Put -Headers $headers -Body $updatedClient -ContentType "application/json"
    Write-Host "   ✅ Configuration mise à jour" -ForegroundColor Green
    
    # 5. Vérification finale
    Write-Host "4. Vérification de la configuration..." -ForegroundColor Yellow
    $updatedClientData = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$clientUuid" -Method Get -Headers $headers
    
    Write-Host "   Client ID: $($updatedClientData.clientId)" -ForegroundColor Gray
    Write-Host "   Public Client: $($updatedClientData.publicClient)" -ForegroundColor Gray
    Write-Host "   Standard Flow: $($updatedClientData.standardFlowEnabled)" -ForegroundColor Gray
    Write-Host "   Redirect URIs:" -ForegroundColor Gray
    foreach ($uri in $updatedClientData.redirectUris) {
        Write-Host "     - $uri" -ForegroundColor Gray
    }
    
    Write-Host ""
    Write-Host "🎉 CONFIGURATION CORRIGÉE AVEC SUCCÈS !" -ForegroundColor Green
    Write-Host ""
    Write-Host "Redémarrez l'application mobile et testez à nouveau la connexion." -ForegroundColor Cyan
    
} catch {
    Write-Host ""
    Write-Host "❌ ERREUR: $($_.Exception.Message)" -ForegroundColor Red
    if ($_.Exception.Response) {
        $statusCode = $_.Exception.Response.StatusCode.value__
        Write-Host "Code de statut HTTP: $statusCode" -ForegroundColor Red
    }
}
