# Keycloak - Lire les rôles et la config du realm unionflow
# Usage: .\keycloak_get_roles.ps1
# Prérequis: Keycloak sur http://localhost:8180, admin/admin

$baseUrl = 'http://localhost:8180'
$body = @{
  username   = 'admin'
  password   = 'admin'
  grant_type = 'password'
  client_id  = 'admin-cli'
}

Write-Host "1. Obtention du token admin (realm master)..." -ForegroundColor Cyan
try {
  $tokenResponse = Invoke-RestMethod -Uri "$baseUrl/realms/master/protocol/openid-connect/token" -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded'
  $token = $tokenResponse.access_token
  Write-Host "   Token obtenu (expire dans $($tokenResponse.expires_in) s)" -ForegroundColor Green
} catch {
  Write-Host "   Erreur: $_" -ForegroundColor Red
  exit 1
}

Write-Host "`n2. Rôles du realm unionflow:" -ForegroundColor Cyan
try {
  $roles = Invoke-RestMethod -Uri "$baseUrl/admin/realms/unionflow/roles" -Headers @{ Authorization = "Bearer $token" }
  $roles | ForEach-Object { Write-Host "   - $($_.name)" }
  if (-not $roles) { Write-Host "   (aucun rôle ou realm inexistant)" -ForegroundColor Yellow }
} catch {
  Write-Host "   Erreur: $_" -ForegroundColor Red
}

Write-Host "`n3. Config du realm unionflow (realm, displayName):" -ForegroundColor Cyan
try {
  $realm = Invoke-RestMethod -Uri "$baseUrl/admin/realms/unionflow" -Headers @{ Authorization = "Bearer $token" }
  Write-Host "   realm: $($realm.realm)"
  Write-Host "   displayName: $($realm.displayName)"
} catch {
  Write-Host "   Erreur: $_" -ForegroundColor Red
}

Write-Host "`nTerminé." -ForegroundColor Green
