param(
    [Alias('r')]
    [string]$Report = ''
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Load shared utilities
$utilsPath = Join-Path $PSScriptRoot '..\lib\utils.ps1'
. $utilsPath

& .\scripts\Windows\starter.ps1
if ($LASTEXITCODE -ne 0) {
    exit $LASTEXITCODE
}

$omitPattern = 'storefront/*,monitoring/*,Dockerfiles/*,*/__init__.py,*/tests/*,*/migrations/*,manage.py,evibes/*'

if (-not $PSBoundParameters.ContainsKey('Report') -or [string]::IsNullOrWhiteSpace($Report)) {
    Write-Step "Running tests with coverage..."

    Write-Info "  → Erasing previous coverage data..."
    docker compose exec app uv run coverage erase
    if ($LASTEXITCODE -ne 0) {
        Write-Error-Custom "Failed to erase coverage data"
        exit $LASTEXITCODE
    }

    Write-Info "  → Running tests..."
    docker compose exec app uv run coverage run --source='.' --omit=$omitPattern manage.py test
    if ($LASTEXITCODE -ne 0) {
        Write-Error-Custom "Tests failed"
        exit $LASTEXITCODE
    }

    Write-Info "  → Generating coverage report..."
    docker compose exec app uv run coverage report -m
    exit $LASTEXITCODE
}

switch ($Report.ToLowerInvariant()) {
    'xml' {
        Write-Step "Generating XML coverage report..."
        docker compose exec app uv run coverage xml --omit=$omitPattern
        if ($LASTEXITCODE -eq 0) {
            Write-Success "XML coverage report generated"
        } else {
            Write-Error-Custom "Failed to generate XML coverage report"
        }
        exit $LASTEXITCODE
    }
    'html' {
        Write-Step "Generating HTML coverage report..."
        docker compose exec app uv run coverage html --omit=$omitPattern
        if ($LASTEXITCODE -eq 0) {
            Write-Success "HTML coverage report generated"
        } else {
            Write-Error-Custom "Failed to generate HTML coverage report"
        }
        exit $LASTEXITCODE
    }
    default {
        Write-Error-Custom "Invalid -Report/-r value '$Report'. Expected 'xml' or 'html'."
        exit 1
    }
}
