# Test Keycloak Authentication and API Call

Write-Host "=== Test d'authentification Keycloak ===" -ForegroundColor Green

# 1. Obtenir un token admin
Write-Host "1. Obtention du token admin..." -ForegroundColor Yellow
try {
    $adminTokenResponse = Invoke-RestMethod -Uri "http://localhost:8180/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"
    $adminToken = $adminTokenResponse.access_token
    Write-Host "✓ Token admin obtenu" -ForegroundColor Green
} catch {
    Write-Host "Erreur lors de l'obtention du token admin: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 2. Créer un utilisateur de test
Write-Host "2. Création d'un utilisateur de test..." -ForegroundColor Yellow
$testUser = @{
    username = "testuser"
    email = "test@unionflow.com"
    firstName = "Test"
    lastName = "User"
    enabled = $true
    credentials = @(
        @{
            type = "password"
            value = "testpass"
            temporary = $false
        }
    )
} | ConvertTo-Json -Depth 3

try {
    $headers = @{
        "Authorization" = "Bearer $adminToken"
        "Content-Type" = "application/json"
    }
    
    Invoke-RestMethod -Uri "http://localhost:8180/admin/realms/unionflow/users" -Method Post -Body $testUser -Headers $headers
    Write-Host "✓ Utilisateur de test créé" -ForegroundColor Green
} catch {
    if ($_.Exception.Response.StatusCode -eq 409) {
        Write-Host "✓ Utilisateur de test existe déjà" -ForegroundColor Green
    } else {
        Write-Host "Erreur lors de la creation de l'utilisateur: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 3. Configurer le client unionflow-server pour permettre les direct access grants
Write-Host "3. Configuration du client unionflow-server..." -ForegroundColor Yellow
try {
    # Obtenir l'ID du client
    $clients = Invoke-RestMethod -Uri "http://localhost:8180/admin/realms/unionflow/clients?clientId=unionflow-server" -Headers $headers
    if ($clients.Count -gt 0) {
        $clientId = $clients[0].id
        
        # Mettre à jour le client pour permettre les direct access grants
        $clientUpdate = @{
            directAccessGrantsEnabled = $true
            publicClient = $true
        } | ConvertTo-Json
        
        Invoke-RestMethod -Uri "http://localhost:8180/admin/realms/unionflow/clients/$clientId" -Method Put -Body $clientUpdate -Headers $headers
        Write-Host "✓ Client unionflow-server configuré" -ForegroundColor Green
    }
} catch {
    Write-Host "Erreur lors de la configuration du client: $($_.Exception.Message)" -ForegroundColor Yellow
}

# 4. Obtenir un token utilisateur
Write-Host "4. Obtention d'un token utilisateur..." -ForegroundColor Yellow
try {
    $userTokenResponse = Invoke-RestMethod -Uri "http://localhost:8180/realms/unionflow/protocol/openid-connect/token" -Method Post -Body "username=testuser&password=testpass&grant_type=password&client_id=unionflow-server" -ContentType "application/x-www-form-urlencoded"
    $userToken = $userTokenResponse.access_token
    Write-Host "✓ Token utilisateur obtenu" -ForegroundColor Green
    Write-Host "Token: $($userToken.Substring(0, 50))..." -ForegroundColor Cyan
} catch {
    Write-Host "Erreur lors de l'obtention du token utilisateur: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Réponse: $($_.Exception.Response)" -ForegroundColor Red
    exit 1
}

# 5. Tester l'appel API avec le token
Write-Host "5. Test de l'appel API avec authentification..." -ForegroundColor Yellow
try {
    $apiHeaders = @{
        "Authorization" = "Bearer $userToken"
        "Content-Type" = "application/json"
    }
    
    $apiResponse = Invoke-RestMethod -Uri "http://localhost:8080/api/evenements/publics" -Headers $apiHeaders
    Write-Host "✓ Appel API réussi !" -ForegroundColor Green
    Write-Host "Nombre d'événements: $($apiResponse.Count)" -ForegroundColor Cyan
} catch {
    Write-Host "Erreur lors de l'appel API: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "Code de statut: $($_.Exception.Response.StatusCode)" -ForegroundColor Red
}

Write-Host "=== Test terminé ===" -ForegroundColor Green
