# Script PowerShell pour tester les endpoints Finance Workflow via Swagger UI
# À exécuter APRÈS le démarrage de Quarkus

param(
    [string]$BaseUrl = "http://localhost:8085",
    [string]$OrganizationId = "00000000-0000-0000-0000-000000000001"
)

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "Finance Workflow - Tests Endpoints REST" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Base URL: $BaseUrl" -ForegroundColor Gray
Write-Host ""

# Fonction utilitaire pour tester un endpoint
function Test-Endpoint {
    param(
        [string]$Name,
        [string]$Method,
        [string]$Url,
        [object]$Body = $null,
        [int[]]$ExpectedStatuses = @(200)
    )

    Write-Host "[$Method] $Name" -ForegroundColor Yellow
    Write-Host "  URL: $Url" -ForegroundColor Gray

    try {
        $params = @{
            Uri = $Url
            Method = $Method
            ContentType = "application/json"
            ErrorAction = "Stop"
        }

        if ($Body) {
            $params.Body = ($Body | ConvertTo-Json -Depth 10)
            Write-Host "  Body: $($params.Body)" -ForegroundColor Gray
        }

        $response = Invoke-RestMethod @params
        $statusCode = 200

        if ($ExpectedStatuses -contains $statusCode) {
            Write-Host "  ✓ Succès (200 OK)" -ForegroundColor Green
            if ($response) {
                Write-Host "  Response: $($response | ConvertTo-Json -Depth 3 -Compress)" -ForegroundColor Gray
            }
            return $true
        } else {
            Write-Host "  ⚠ Status inattendu: $statusCode" -ForegroundColor Yellow
            return $false
        }
    }
    catch {
        $statusCode = $_.Exception.Response.StatusCode.value__

        if ($ExpectedStatuses -contains $statusCode) {
            Write-Host "  ✓ Status attendu: $statusCode" -ForegroundColor Green
            return $true
        } else {
            Write-Host "  ✗ Erreur: $statusCode - $($_.Exception.Message)" -ForegroundColor Red
            return $false
        }
    }
    finally {
        Write-Host ""
    }
}

# Tests des endpoints

$results = @{
    Total = 0
    Passed = 0
    Failed = 0
}

Write-Host "=== Tests Approbations ===" -ForegroundColor Cyan
Write-Host ""

# TEST 1: GET Approbations en attente
$results.Total++
if (Test-Endpoint `
    -Name "Lister les approbations en attente" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/approvals/pending?organizationId=$OrganizationId" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

# TEST 2: GET Nombre d'approbations en attente
$results.Total++
if (Test-Endpoint `
    -Name "Compter les approbations en attente" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/approvals/count/pending?organizationId=$OrganizationId" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

# TEST 3: GET Historique des approbations
$results.Total++
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ss")
$endDate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ss")
if (Test-Endpoint `
    -Name "Historique des approbations" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/approvals/history?organizationId=$OrganizationId&startDate=$startDate&endDate=$endDate" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

Write-Host "=== Tests Budgets ===" -ForegroundColor Cyan
Write-Host ""

# TEST 4: GET Liste des budgets
$results.Total++
if (Test-Endpoint `
    -Name "Lister les budgets" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/budgets?organizationId=$OrganizationId" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

# TEST 5: GET Budgets filtrés par statut
$results.Total++
if (Test-Endpoint `
    -Name "Lister les budgets actifs" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/budgets?organizationId=$OrganizationId&status=ACTIVE" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

# TEST 6: GET Budgets filtrés par année
$results.Total++
$currentYear = (Get-Date).Year
if (Test-Endpoint `
    -Name "Lister les budgets de l'année courante" `
    -Method "GET" `
    -Url "$BaseUrl/api/finance/budgets?organizationId=$OrganizationId&year=$currentYear" `
    -ExpectedStatuses @(200, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

Write-Host "=== Tests Validation ===" -ForegroundColor Cyan
Write-Host ""

# TEST 7: POST Budget invalide (sans lignes)
$results.Total++
$invalidBudget = @{
    name = "Budget Test Invalide"
    organizationId = $OrganizationId
    period = "MONTHLY"
    year = $currentYear
    month = 3
    currency = "XOF"
    lines = @()
}
if (Test-Endpoint `
    -Name "Créer budget invalide (sans lignes)" `
    -Method "POST" `
    -Url "$BaseUrl/api/finance/budgets" `
    -Body $invalidBudget `
    -ExpectedStatuses @(400, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

# TEST 8: POST Budget invalide (période invalide)
$results.Total++
$invalidBudget2 = @{
    name = "Budget Test"
    organizationId = $OrganizationId
    period = "INVALID_PERIOD"
    year = $currentYear
    currency = "XOF"
    lines = @(
        @{
            category = "CONTRIBUTIONS"
            name = "Test"
            amountPlanned = 1000000.00
        }
    )
}
if (Test-Endpoint `
    -Name "Créer budget avec période invalide" `
    -Method "POST" `
    -Url "$BaseUrl/api/finance/budgets" `
    -Body $invalidBudget2 `
    -ExpectedStatuses @(400, 401, 403)) {
    $results.Passed++
} else {
    $results.Failed++
}

Write-Host "=== Tests Swagger UI ===" -ForegroundColor Cyan
Write-Host ""

# TEST 9: Vérifier que Swagger UI est accessible
$results.Total++
Write-Host "[GET] Swagger UI accessible" -ForegroundColor Yellow
Write-Host "  URL: $BaseUrl/q/swagger-ui" -ForegroundColor Gray
try {
    $swaggerResponse = Invoke-WebRequest -Uri "$BaseUrl/q/swagger-ui" -ErrorAction Stop
    if ($swaggerResponse.StatusCode -eq 200) {
        Write-Host "  ✓ Swagger UI accessible" -ForegroundColor Green
        $results.Passed++
    }
} catch {
    Write-Host "  ✗ Swagger UI inaccessible" -ForegroundColor Red
    $results.Failed++
}
Write-Host ""

# TEST 10: Vérifier que l'OpenAPI spec contient Finance Workflow
$results.Total++
Write-Host "[GET] OpenAPI spec contient Finance Workflow" -ForegroundColor Yellow
Write-Host "  URL: $BaseUrl/q/openapi" -ForegroundColor Gray
try {
    $openApiSpec = Invoke-RestMethod -Uri "$BaseUrl/q/openapi" -ErrorAction Stop
    $specJson = $openApiSpec | ConvertTo-Json -Depth 10

    if ($specJson -match "approval-resource" -and $specJson -match "budget-resource") {
        Write-Host "  ✓ Finance Workflow endpoints trouvés dans OpenAPI" -ForegroundColor Green
        $results.Passed++
    } else {
        Write-Host "  ✗ Finance Workflow endpoints non trouvés" -ForegroundColor Red
        $results.Failed++
    }
} catch {
    Write-Host "  ✗ Erreur lors de la récupération de l'OpenAPI spec" -ForegroundColor Red
    $results.Failed++
}
Write-Host ""

# Résumé
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "RÉSUMÉ DES TESTS" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Total: $($results.Total) tests" -ForegroundColor Gray
Write-Host "Réussis: $($results.Passed) tests" -ForegroundColor Green
Write-Host "Échoués: $($results.Failed) tests" -ForegroundColor Red
Write-Host ""

if ($results.Failed -eq 0) {
    Write-Host "✓ TOUS LES TESTS SONT PASSÉS !" -ForegroundColor Green
    Write-Host ""
    Write-Host "Prochaine étape: Tester avec l'app mobile Flutter" -ForegroundColor Yellow
    exit 0
} else {
    $passRate = [math]::Round(($results.Passed / $results.Total) * 100, 2)
    Write-Host "⚠ Taux de réussite: $passRate%" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Vérifiez les erreurs ci-dessus et consultez:" -ForegroundColor Yellow
    Write-Host "  - Logs Quarkus pour les détails des erreurs" -ForegroundColor Gray
    Write-Host "  - Swagger UI: $BaseUrl/q/swagger-ui" -ForegroundColor Gray
    exit 1
}
