# Script final pour corriger les redirect URIs Keycloak
$KeycloakUrl = "http://192.168.1.11:8180"
$Realm = "unionflow"
$ClientId = "unionflow-mobile"
$ClientUuid = "67b09521-3c8d-4ab1-9d13-80af9240c64d"

Write-Host "=== CORRECTION FINALE KEYCLOAK ===" -ForegroundColor Cyan

try {
    # Obtenir token admin
    $tokenResponse = Invoke-RestMethod -Uri "$KeycloakUrl/realms/master/protocol/openid-connect/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body "username=admin&password=admin&grant_type=password&client_id=admin-cli"
    $accessToken = $tokenResponse.access_token
    Write-Host "✅ Token obtenu" -ForegroundColor Green
    
    # Configuration correcte du client
    $headers = @{ "Authorization" = "Bearer $accessToken" }
    
    $clientConfig = @{
        id = $ClientUuid
        clientId = $ClientId
        name = "UnionFlow Mobile App"
        enabled = $true
        publicClient = $true
        standardFlowEnabled = $true
        implicitFlowEnabled = $false
        directAccessGrantsEnabled = $false
        serviceAccountsEnabled = $false
        redirectUris = @(
            "dev.lions.unionflow_mobile_apps://callback",
            "dev.lions.unionflow_mobile_apps://login-callback",
            "dev.lions.unionflow_mobile_apps://oauth/callback"
        )
        webOrigins = @("+")
        attributes = @{
            "pkce.code.challenge.method" = "S256"
        }
        protocol = "openid-connect"
        fullScopeAllowed = $true
        defaultClientScopes = @("web-origins", "acr", "profile", "roles", "basic", "email")
        optionalClientScopes = @("address", "phone", "offline_access", "organization", "microprofile-jwt")
    }
    
    $clientJson = $clientConfig | ConvertTo-Json -Depth 10
    
    # Mettre à jour le client
    Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$ClientUuid" -Method Put -Headers $headers -Body $clientJson -ContentType "application/json"
    
    Write-Host "✅ Client mis à jour avec succès !" -ForegroundColor Green
    Write-Host ""
    Write-Host "Nouvelles redirect URIs:" -ForegroundColor Yellow
    Write-Host "  - dev.lions.unionflow_mobile_apps://callback" -ForegroundColor Gray
    Write-Host "  - dev.lions.unionflow_mobile_apps://login-callback" -ForegroundColor Gray
    Write-Host "  - dev.lions.unionflow_mobile_apps://oauth/callback" -ForegroundColor Gray
    
} catch {
    Write-Host "❌ Erreur: $($_.Exception.Message)" -ForegroundColor Red
    if ($_.Exception.Response) {
        $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
        $responseBody = $reader.ReadToEnd()
        Write-Host "Détails: $responseBody" -ForegroundColor Red
    }
}
