# Script PowerShell pour configurer le client Keycloak
# Usage: .\setup-keycloak-client.ps1

# Configuration
$KEYCLOAK_URL = "http://localhost:8180"
$ADMIN_USER = "admin"
$ADMIN_PASSWORD = "admin"
$REALM = "master"
$CLIENT_ID = "lions-user-manager"
$CLIENT_SECRET = "dev-secret-change-me"

Write-Host "=== Configuration du client Keycloak ===" -ForegroundColor Cyan
Write-Host "Keycloak URL: $KEYCLOAK_URL"
Write-Host "Realm: $REALM"
Write-Host "Client ID: $CLIENT_ID"
Write-Host ""

# Obtenir le token admin
Write-Host "1. Connexion à Keycloak..." -ForegroundColor Yellow
try {
    $tokenResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/realms/master/protocol/openid-connect/token" `
        -Method Post `
        -ContentType "application/x-www-form-urlencoded" `
        -Body @{
            grant_type = "password"
            client_id = "admin-cli"
            username = $ADMIN_USER
            password = $ADMIN_PASSWORD
        }
    
    $accessToken = $tokenResponse.access_token
    $headers = @{
        "Authorization" = "Bearer $accessToken"
        "Content-Type" = "application/json"
    }
    Write-Host "   ✓ Connecté" -ForegroundColor Green
} catch {
    Write-Host "   ✗ Erreur de connexion: $_" -ForegroundColor Red
    exit 1
}

# Vérifier si le client existe déjà
Write-Host "2. Vérification du client existant..." -ForegroundColor Yellow
$existingClients = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients?clientId=$CLIENT_ID" `
    -Method Get `
    -Headers $headers `
    -ErrorAction SilentlyContinue

if ($existingClients -and $existingClients.Count -gt 0) {
    $clientUuid = $existingClients[0].id
    Write-Host "   ✓ Client existe déjà (UUID: $clientUuid)" -ForegroundColor Green
    
    # Récupérer le secret existant
    Write-Host "3. Récupération du secret..." -ForegroundColor Yellow
    try {
        $secretResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$clientUuid/client-secret" `
            -Method Get `
            -Headers $headers
        
        $currentSecret = $secretResponse.value
        Write-Host "   ✓ Secret actuel: $currentSecret" -ForegroundColor Green
        Write-Host ""
        Write-Host "   Vérifiez que ce secret correspond à celui dans application-dev.properties" -ForegroundColor Yellow
        Write-Host "   quarkus.oidc.credentials.secret=$currentSecret" -ForegroundColor White
    } catch {
        Write-Host "   ⚠ Erreur lors de la récupération du secret: $_" -ForegroundColor Yellow
        Write-Host "   Vous pouvez récupérer le secret manuellement dans l'interface Keycloak" -ForegroundColor Yellow
    }
} else {
    # Créer le client
    Write-Host "3. Création du client..." -ForegroundColor Yellow
    $clientBody = @{
        clientId = $CLIENT_ID
        enabled = $true
        serviceAccountsEnabled = $true
        standardFlowEnabled = $false
        directAccessGrantsEnabled = $false
        publicClient = $false
        protocol = "openid-connect"
    } | ConvertTo-Json
    
    try {
        $createResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients" `
            -Method Post `
            -Headers $headers `
            -Body $clientBody
        
        Write-Host "   ✓ Client créé avec succès" -ForegroundColor Green
        
        # Récupérer l'UUID du client créé
        Start-Sleep -Seconds 1
        $clients = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients?clientId=$CLIENT_ID" `
            -Method Get `
            -Headers $headers
        
        $clientUuid = $clients[0].id
        Write-Host "   Client UUID: $clientUuid" -ForegroundColor Cyan
        
        # Récupérer le secret généré automatiquement
        Write-Host "4. Récupération du secret..." -ForegroundColor Yellow
        Start-Sleep -Seconds 1
        try {
            $secretResponse = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$clientUuid/client-secret" `
                -Method Get `
                -Headers $headers
            
            $generatedSecret = $secretResponse.value
            Write-Host "   ✓ Secret généré automatiquement: $generatedSecret" -ForegroundColor Green
            Write-Host ""
            Write-Host "   IMPORTANT: Mettez à jour application-dev.properties avec ce secret:" -ForegroundColor Yellow
            Write-Host "   quarkus.oidc.credentials.secret=$generatedSecret" -ForegroundColor White
            
            # Si vous voulez utiliser un secret personnalisé, décommentez les lignes suivantes:
            # $secretBody = @{
            #     value = $CLIENT_SECRET
            # } | ConvertTo-Json
            # 
            # Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/clients/$clientUuid/client-secret" `
            #     -Method Put `
            #     -Headers $headers `
            #     -Body $secretBody
            # Write-Host "   ✓ Secret personnalisé configuré: $CLIENT_SECRET" -ForegroundColor Green
        } catch {
            Write-Host "   ⚠ Erreur lors de la récupération du secret: $_" -ForegroundColor Yellow
            Write-Host "   Vous pouvez récupérer le secret manuellement dans l'interface Keycloak" -ForegroundColor Yellow
        }
    } catch {
        Write-Host "   ✗ Erreur lors de la création du client: $_" -ForegroundColor Red
        exit 1
    }
}

# Attribuer le rôle admin au service account
Write-Host "5. Attribution du rôle admin au service account..." -ForegroundColor Yellow
$serviceAccountUsername = "service-account-$CLIENT_ID"
$users = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users?username=$serviceAccountUsername" `
    -Method Get `
    -Headers $headers `
    -ErrorAction SilentlyContinue

if ($users -and $users.Count -gt 0) {
    $serviceAccountId = $users[0].id
    
    # Récupérer le rôle admin
    $adminRole = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/roles/admin" `
        -Method Get `
        -Headers $headers
    
    # Vérifier si le rôle est déjà assigné
    $currentRoles = Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$serviceAccountId/role-mappings/realm" `
        -Method Get `
        -Headers $headers `
        -ErrorAction SilentlyContinue
    
    $hasAdminRole = $currentRoles | Where-Object { $_.id -eq $adminRole.id }
    
    if (-not $hasAdminRole) {
        $roleBody = @($adminRole) | ConvertTo-Json
        
        Invoke-RestMethod -Uri "$KEYCLOAK_URL/admin/realms/$REALM/users/$serviceAccountId/role-mappings/realm" `
            -Method Post `
            -Headers $headers `
            -Body $roleBody
        
        Write-Host "   ✓ Rôle admin attribué" -ForegroundColor Green
    } else {
        Write-Host "   ✓ Rôle admin déjà attribué" -ForegroundColor Green
    }
} else {
    Write-Host "   ⚠ Service account non trouvé. Il sera créé automatiquement lors de la première utilisation." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "=== Configuration terminée! ===" -ForegroundColor Green
Write-Host ""
Write-Host "Vérifiez que le secret dans application-dev.properties correspond:" -ForegroundColor Cyan
Write-Host "  quarkus.oidc.credentials.secret=$CLIENT_SECRET" -ForegroundColor White
Write-Host ""
Write-Host "Redémarrez le serveur Quarkus pour appliquer les changements." -ForegroundColor Cyan

