# Script simple pour corriger les redirect URIs
$KeycloakUrl = "http://192.168.1.11:8180"
$Realm = "unionflow"
$ClientId = "unionflow-mobile"

Write-Host "=== CORRECTION REDIRECT URIs ===" -ForegroundColor Cyan

try {
    # Obtenir token admin
    $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
    
    # Récupérer le client
    $headers = @{ "Authorization" = "Bearer $accessToken" }
    $clients = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients?clientId=$ClientId" -Method Get -Headers $headers
    $client = $clients[0]
    $clientUuid = $client.id
    
    Write-Host "Client trouvé: $clientUuid" -ForegroundColor Green
    Write-Host "Redirect URIs actuelles:" -ForegroundColor Yellow
    foreach ($uri in $client.redirectUris) {
        Write-Host "  - $uri" -ForegroundColor Gray
    }
    
    # Mise à jour simple des redirect URIs
    $client.redirectUris = @(
        "com.unionflow.mobile://login-callback",
        "com.unionflow.mobile://login-callback/*",
        "com.unionflow.mobile://oauth/callback",
        "com.unionflow.mobile://oauth/callback/*"
    )
    
    $client.postLogoutRedirectUris = @(
        "com.unionflow.mobile://logout-callback",
        "com.unionflow.mobile://logout-callback/*"
    )
    
    # Assurer que c'est un client public avec PKCE
    $client.publicClient = $true
    $client.standardFlowEnabled = $true
    $client.directAccessGrantsEnabled = $false
    
    if (-not $client.attributes) {
        $client.attributes = @{}
    }
    $client.attributes["pkce.code.challenge.method"] = "S256"
    
    $clientJson = $client | ConvertTo-Json -Depth 10
    
    # Appliquer la mise à jour
    Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$clientUuid" -Method Put -Headers $headers -Body $clientJson -ContentType "application/json"
    
    Write-Host ""
    Write-Host "✅ Redirect URIs mis à jour:" -ForegroundColor Green
    Write-Host "  - com.unionflow.mobile://login-callback" -ForegroundColor Gray
    Write-Host "  - com.unionflow.mobile://login-callback/*" -ForegroundColor Gray
    Write-Host "  - com.unionflow.mobile://oauth/callback" -ForegroundColor Gray
    Write-Host "  - com.unionflow.mobile://oauth/callback/*" -ForegroundColor Gray
    
} catch {
    Write-Host "Erreur: $($_.Exception.Message)" -ForegroundColor Red
}
