# Configuration rapide des rôles UnionFlow dans Keycloak
$KEYCLOAK_URL = "http://192.168.1.145:8180"
$REALM = "unionflow"

# Obtenir un nouveau token
Write-Host "Obtention du token..." -ForegroundColor Blue
$tokenResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" -Method Post -Body @{
    username = "admin"
    password = "admin"
    grant_type = "password"
    client_id = "admin-cli"
} -ContentType "application/x-www-form-urlencoded"

$token = $tokenResponse.access_token
Write-Host "Token obtenu: $($token.Substring(0,50))..." -ForegroundColor Green

# Headers pour les requêtes
$headers = @{
    "Authorization" = "Bearer $token"
    "Content-Type" = "application/json"
}

# Créer les rôles
Write-Host "`nCréation des rôles..." -ForegroundColor Blue

$roles = @(
    @{ name = "SUPER_ADMINISTRATEUR"; description = "Super Administrateur - Accès système complet"; level = "100" },
    @{ name = "ADMINISTRATEUR_ORGANISATION"; description = "Administrateur Organisation - Gestion complète organisation"; level = "85" },
    @{ name = "RESPONSABLE_TECHNIQUE"; description = "Responsable Technique - Configuration et workflows"; level = "80" },
    @{ name = "RESPONSABLE_FINANCIER"; description = "Responsable Financier - Gestion finances et budget"; level = "75" },
    @{ name = "RESPONSABLE_MEMBRES"; description = "Responsable Membres - Gestion communauté"; level = "70" },
    @{ name = "MEMBRE_ACTIF"; description = "Membre Actif - Participation et organisation"; level = "50" },
    @{ name = "MEMBRE_SIMPLE"; description = "Membre Simple - Participation standard"; level = "30" },
    @{ name = "VISITEUR"; description = "Visiteur - Accès public découverte"; level = "0" }
)

foreach ($role in $roles) {
    try {
        $roleData = @{
            name = $role.name
            description = $role.description
            attributes = @{
                level = @($role.level)
                hierarchy = @($role.level)
            }
        } | ConvertTo-Json -Depth 3
        
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles" -Method Post -Body $roleData -Headers $headers
        Write-Host "✓ Rôle créé: $($role.name)" -ForegroundColor Green
    }
    catch {
        Write-Host "⚠ Rôle $($role.name): $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

# Créer les utilisateurs
Write-Host "`nCréation des utilisateurs..." -ForegroundColor Blue

$users = @(
    @{ username = "superadmin"; email = "superadmin@unionflow.dev"; password = "SuperAdmin123!"; firstName = "Super"; lastName = "Admin"; role = "SUPER_ADMINISTRATEUR" },
    @{ username = "admin.org"; email = "admin@association-dev.fr"; password = "AdminOrg123!"; firstName = "Admin"; lastName = "Organisation"; role = "ADMINISTRATEUR_ORGANISATION" },
    @{ username = "tech.lead"; email = "tech@association-dev.fr"; password = "TechLead123!"; firstName = "Tech"; lastName = "Lead"; role = "RESPONSABLE_TECHNIQUE" },
    @{ username = "tresorier"; email = "tresorier@association-dev.fr"; password = "Tresorier123!"; firstName = "Trésorier"; lastName = "Finance"; role = "RESPONSABLE_FINANCIER" },
    @{ username = "rh.manager"; email = "rh@association-dev.fr"; password = "RhManager123!"; firstName = "RH"; lastName = "Manager"; role = "RESPONSABLE_MEMBRES" },
    @{ username = "marie.active"; email = "marie@association-dev.fr"; password = "Marie123!"; firstName = "Marie"; lastName = "Active"; role = "MEMBRE_ACTIF" },
    @{ username = "jean.simple"; email = "jean@association-dev.fr"; password = "Jean123!"; firstName = "Jean"; lastName = "Simple"; role = "MEMBRE_SIMPLE" },
    @{ username = "visiteur"; email = "visiteur@example.com"; password = "Visiteur123!"; firstName = "Visiteur"; lastName = "Public"; role = "VISITEUR" }
)

foreach ($user in $users) {
    try {
        $userData = @{
            username = $user.username
            email = $user.email
            firstName = $user.firstName
            lastName = $user.lastName
            enabled = $true
            emailVerified = $true
            credentials = @(
                @{
                    type = "password"
                    value = $user.password
                    temporary = $false
                }
            )
        } | ConvertTo-Json -Depth 3
        
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users" -Method Post -Body $userData -Headers $headers
        Write-Host "✓ Utilisateur créé: $($user.username)" -ForegroundColor Green
        
        # Assigner le rôle
        Start-Sleep -Milliseconds 500  # Petite pause pour éviter les conflits
        
        # Obtenir l'ID de l'utilisateur
        $userSearch = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=$($user.username)" -Method Get -Headers $headers
        if ($userSearch.Count -gt 0) {
            $userId = $userSearch[0].id
            
            # Obtenir le rôle
            $roleInfo = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles/$($user.role)" -Method Get -Headers $headers
            
            # Assigner le rôle
            $roleAssignment = @(
                @{
                    id = $roleInfo.id
                    name = $roleInfo.name
                }
            ) | ConvertTo-Json -Depth 2
            
            Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$userId/role-mappings/realm" -Method Post -Body $roleAssignment -Headers $headers
            Write-Host "  → Rôle $($user.role) assigné" -ForegroundColor Cyan
        }
    }
    catch {
        Write-Host "⚠ Utilisateur $($user.username): $($_.Exception.Message)" -ForegroundColor Yellow
    }
}

Write-Host "`n============================================================================" -ForegroundColor Green
Write-Host "✅ CONFIGURATION TERMINÉE" -ForegroundColor Green
Write-Host "============================================================================" -ForegroundColor Green
Write-Host "`n🔐 COMPTES DE TEST CRÉÉS :" -ForegroundColor White
foreach ($user in $users) {
    Write-Host "• $($user.email) ($($user.role))" -ForegroundColor White
}
Write-Host "`n🚀 Vous pouvez maintenant tester l'authentification !" -ForegroundColor Green
