# Script pour lister les rôles des utilisateurs Keycloak
# Usage: .\list-user-roles.ps1 [username]
# Exemple: .\list-user-roles.ps1 admin.meska@unionflow.test

param(
    [string]$Username = ""
)

Write-Host "=== Rôles des Utilisateurs (Realm: unionflow) ===" -ForegroundColor Cyan
Write-Host ""

# Obtenir le token admin
$tokenResponse = Invoke-RestMethod -Method Post `
    -Uri 'http://localhost:8180/realms/master/protocol/openid-connect/token' `
    -ContentType 'application/x-www-form-urlencoded' `
    -Body 'username=admin&password=admin&grant_type=password&client_id=admin-cli'

$token = $tokenResponse.access_token

# Récupérer les utilisateurs
$users = Invoke-RestMethod -Method Get `
    -Uri 'http://localhost:8180/admin/realms/unionflow/users' `
    -Headers @{ Authorization = "Bearer $token" }

# Filtrer si un username est spécifié
if ($Username) {
    $users = $users | Where-Object { $_.username -eq $Username }
    if (-not $users) {
        Write-Host "[ERREUR] Utilisateur '$Username' non trouvé" -ForegroundColor Red
        exit 1
    }
}

# Parcourir les utilisateurs
foreach ($user in $users) {
    Write-Host "[$($user.username)]" -ForegroundColor Yellow
    Write-Host "  Email: $($user.email)"
    Write-Host "  Enabled: $($user.enabled)"

    # Realm roles
    $realmRoles = Invoke-RestMethod -Method Get `
        -Uri "http://localhost:8180/admin/realms/unionflow/users/$($user.id)/role-mappings/realm" `
        -Headers @{ Authorization = "Bearer $token" }

    if ($realmRoles) {
        Write-Host "  Rôles:"
        $realmRoles | Where-Object { $_.name -ne 'default-roles-unionflow' -and $_.name -ne 'offline_access' -and $_.name -ne 'uma_authorization' } | ForEach-Object {
            Write-Host "    - $($_.name)" -ForegroundColor Green
        }
    }

    Write-Host ""
}

Write-Host "=== Rôles Disponibles ===" -ForegroundColor Cyan
$allRoles = Invoke-RestMethod -Method Get `
    -Uri "http://localhost:8180/admin/realms/unionflow/roles" `
    -Headers @{ Authorization = "Bearer $token" }

$allRoles | Where-Object { $_.name -notlike 'default-*' -and $_.name -ne 'offline_access' -and $_.name -ne 'uma_authorization' } | ForEach-Object {
    Write-Host "  - $($_.name)"
}
