# Script pour corriger les redirect URIs du client btpxpress-frontend
$KeycloakUrl = "https://security.lions.dev"
$Realm = "btpxpress"
$ClientId = "btpxpress-frontend"
$AdminUser = "admin"
$AdminPassword = "KeycloakAdmin2025!"

Write-Host "🔧 Correction des redirect URIs pour $ClientId..." -ForegroundColor Yellow

try {
    # 1. Obtenir un token admin
    Write-Host "📝 Authentification admin..." -ForegroundColor Gray
    $tokenResponse = Invoke-RestMethod -Uri "$KeycloakUrl/realms/master/protocol/openid-connect/token" -Method Post -Body @{
        username = $AdminUser
        password = $AdminPassword
        grant_type = "password"
        client_id = "admin-cli"
    } -ContentType "application/x-www-form-urlencoded"
    
    $headers = @{
        "Authorization" = "Bearer $($tokenResponse.access_token)"
        "Content-Type" = "application/json"
    }
    
    # 2. Récupérer le client
    Write-Host "🔍 Recherche du client $ClientId..." -ForegroundColor Gray
    $clients = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients?clientId=$ClientId" -Method Get -Headers $headers
    
    if ($clients.Count -eq 0) {
        throw "Client $ClientId non trouvé"
    }
    
    $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
    }
    
    # 3. Mettre à jour les redirect URIs (supprimer /auth/callback)
    $newRedirectUris = @(
        "http://localhost:3000/dashboard",
        "http://localhost:3001/dashboard", 
        "https://btpxpress.lions.dev/dashboard",
        "http://localhost:3000/",
        "http://localhost:3001/",
        "https://btpxpress.lions.dev/"
    )
    
    $updateData = @{
        redirectUris = $newRedirectUris
    }
    
    $updateJson = $updateData | ConvertTo-Json -Depth 10
    
    # 4. Appliquer la mise à jour
    Write-Host "🔄 Mise à jour des redirect URIs..." -ForegroundColor Yellow
    Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$clientUuid" -Method Put -Headers $headers -Body $updateJson
    
    Write-Host ""
    Write-Host "✅ Redirect URIs mis à jour avec succès:" -ForegroundColor Green
    foreach ($uri in $newRedirectUris) {
        Write-Host "   - $uri" -ForegroundColor Gray
    }
    
    Write-Host ""
    Write-Host "🚫 URIs supprimées (obsolètes):" -ForegroundColor Red
    Write-Host "   - http://localhost:3000/auth/callback" -ForegroundColor Gray
    Write-Host "   - http://localhost:3001/auth/callback" -ForegroundColor Gray
    
}
catch {
    Write-Host "❌ Erreur: $($_.Exception.Message)" -ForegroundColor Red
}
