# Script PowerShell de configuration Keycloak - Utilisateur de test
# Utilise l'API Admin REST de Keycloak pour créer l'utilisateur et les rôles

$KEYCLOAK_URL = "http://localhost:8180"
$ADMIN_USER = "admin"
$ADMIN_PASSWORD = "admin"
$REALM = "lions-user-manager"
$TEST_USER = "test-user"
$TEST_PASSWORD = "test123"
$TEST_EMAIL = "test@lions.dev"

Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "Configuration Keycloak - Utilisateur Test" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""

# 1. Obtenir le token d'administration
Write-Host "1. Authentification admin..." -ForegroundColor Yellow
$tokenParams = "username=$ADMIN_USER&password=$ADMIN_PASSWORD&grant_type=password&client_id=admin-cli"
$tokenResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $tokenParams

$ACCESS_TOKEN = $tokenResponse.access_token

if (-not $ACCESS_TOKEN) {
    Write-Host "ERREUR: Impossible d'obtenir le token d'administration" -ForegroundColor Red
    exit 1
}

Write-Host "✓ Token obtenu" -ForegroundColor Green
Write-Host ""

# 2. Vérifier/Créer le realm
Write-Host "2. Vérification du realm '$REALM'..." -ForegroundColor Yellow
$headers = @{Authorization = "Bearer $ACCESS_TOKEN"}
try {
    $realmCheck = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM" -Method Get -Headers $headers -ErrorAction Stop
    Write-Host "✓ Realm existe déjà" -ForegroundColor Green
} catch {
    Write-Host "Création du realm '$REALM'..." -ForegroundColor Yellow
    $realmBody = @{
        realm = $REALM
        enabled = $true
    } | ConvertTo-Json
    
    $headersWithContent = @{Authorization = "Bearer $ACCESS_TOKEN"; "Content-Type" = "application/json"}
    Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms" -Method Post -Headers $headersWithContent -Body $realmBody | Out-Null
    Write-Host "✓ Realm créé" -ForegroundColor Green
}
Write-Host ""

# 3. Créer les rôles realm
Write-Host "3. Création des rôles realm..." -ForegroundColor Yellow
$ROLES = @("admin", "user_manager", "user_viewer", "role_manager", "role_viewer", "auditor", "sync_manager")

foreach ($ROLE in $ROLES) {
    Write-Host "  - Vérification du rôle '$ROLE'..." -ForegroundColor Gray
    try {
        $roleCheck = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles/$ROLE" -Method Get -Headers $headers -ErrorAction Stop
        Write-Host "    ✓ Rôle '$ROLE' existe déjà" -ForegroundColor Green
    } catch {
        $roleBody = @{
            name = $ROLE
            description = "Rôle $ROLE pour lions-user-manager"
        } | ConvertTo-Json
        
        $headersWithContent = @{Authorization = "Bearer $ACCESS_TOKEN"; "Content-Type" = "application/json"}
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles" -Method Post -Headers $headersWithContent -Body $roleBody | Out-Null
        Write-Host "    ✓ Rôle '$ROLE' créé" -ForegroundColor Green
    }
}
Write-Host ""

# 4. Créer l'utilisateur de test
Write-Host "4. Création de l'utilisateur '$TEST_USER'..." -ForegroundColor Yellow
$users = $null
try {
    $users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=$TEST_USER" -Method Get -Headers $headers -ErrorAction Stop
} catch {
    $users = $null
}

if ($users -and $users.Count -gt 0) {
    $USER_ID = $users[0].id
    Write-Host "  ✓ Utilisateur existe déjà (ID: $USER_ID)" -ForegroundColor Green
} else {
    $userBody = @{
        username = $TEST_USER
        email = $TEST_EMAIL
        firstName = "Test"
        lastName = "User"
        enabled = $true
        emailVerified = $true
    } | ConvertTo-Json
    
    $headersWithContent = @{Authorization = "Bearer $ACCESS_TOKEN"; "Content-Type" = "application/json"}
    Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users" -Method Post -Headers $headersWithContent -Body $userBody | Out-Null
    
    $users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=$TEST_USER" -Method Get -Headers $headers
    $USER_ID = $users[0].id
    
    Write-Host "  ✓ Utilisateur créé (ID: $USER_ID)" -ForegroundColor Green
    
    $passwordBody = @{
        type = "password"
        value = $TEST_PASSWORD
        temporary = $false
    } | ConvertTo-Json
    
    Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$USER_ID/reset-password" -Method Put -Headers $headersWithContent -Body $passwordBody | Out-Null
    Write-Host "  ✓ Mot de passe défini" -ForegroundColor Green
}
Write-Host ""

# 5. Assigner les rôles à l'utilisateur
Write-Host "5. Attribution des rôles à l'utilisateur..." -ForegroundColor Yellow

$roleRepresentations = @()
foreach ($ROLE in $ROLES) {
    $roleRep = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles/$ROLE" -Method Get -Headers $headers
    $roleRepresentations += $roleRep
}

$headersWithContent = @{Authorization = "Bearer $ACCESS_TOKEN"; "Content-Type" = "application/json"}
Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$USER_ID/role-mappings/realm" -Method Post -Headers $headersWithContent -Body ($roleRepresentations | ConvertTo-Json) | Out-Null

Write-Host "  ✓ Rôles assignés" -ForegroundColor Green
Write-Host ""

# 6. Vérifier le client et le mapper de rôles
Write-Host "6. Vérification du client 'lions-user-manager-client'..." -ForegroundColor Yellow
try {
    $clients = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients?clientId=lions-user-manager-client" -Method Get -Headers $headers
    
    if ($clients.Count -gt 0) {
        $CLIENT_ID = $clients[0].id
        Write-Host "  ✓ Client trouvé (ID: $CLIENT_ID)" -ForegroundColor Green
        
        $mappers = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$CLIENT_ID/protocol-mappers/models" -Method Get -Headers $headers
        $mapperExists = $mappers | Where-Object { $_.name -eq "realm roles" }
        
        if (-not $mapperExists) {
            Write-Host "  Création du mapper 'realm roles'..." -ForegroundColor Yellow
            $mapperBody = @{
                name = "realm roles"
                protocol = "openid-connect"
                protocolMapper = "oidc-usermodel-realm-role-mapper"
                config = @{
                    "claim.name" = "realm_access.roles"
                    "access.token.claim" = "true"
                    "id.token.claim" = "true"
                    "userinfo.token.claim" = "true"
                }
            } | ConvertTo-Json -Depth 10
            
            Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$CLIENT_ID/protocol-mappers/models" -Method Post -Headers $headersWithContent -Body $mapperBody | Out-Null
            Write-Host "  ✓ Mapper créé" -ForegroundColor Green
        } else {
            Write-Host "  ✓ Mapper existe déjà" -ForegroundColor Green
        }
    } else {
        Write-Host "  ⚠ Client 'lions-user-manager-client' non trouvé" -ForegroundColor Yellow
        Write-Host "  Veuillez créer le client manuellement dans Keycloak" -ForegroundColor Yellow
    }
} catch {
    Write-Host "  ⚠ Erreur lors de la vérification du client: $_" -ForegroundColor Yellow
}
Write-Host ""

Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "Configuration terminée !" -ForegroundColor Green
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Informations de connexion:" -ForegroundColor Yellow
Write-Host "  Username: $TEST_USER"
Write-Host "  Password: $TEST_PASSWORD"
Write-Host "  Email: $TEST_EMAIL"
Write-Host ""
Write-Host "Rôles assignés: $($ROLES -join ', ')" -ForegroundColor Yellow
Write-Host ""
