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

Write-Host "Correction des redirect URIs..." -ForegroundColor Yellow

# 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..." -ForegroundColor Gray
$clients = Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients?clientId=$ClientId" -Method Get -Headers $headers

$client = $clients[0]
$clientUuid = $client.id

Write-Host "Client trouve: $clientUuid" -ForegroundColor Green

# 3. Mettre à jour les redirect URIs
$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 a jour..." -ForegroundColor Yellow
Invoke-RestMethod -Uri "$KeycloakUrl/admin/realms/$Realm/clients/$clientUuid" -Method Put -Headers $headers -Body $updateJson

Write-Host "Redirect URIs mis a jour!" -ForegroundColor Green
