<#
.SYNOPSIS
    Run the MongoDB adapter integration tests against a local Docker MongoDB container.

.DESCRIPTION
    Starts a temporary MongoDB container, runs a targeted pytest suite with
    USE_MONGODB=true, then stops and removes the container.

.EXAMPLE
    cd backend
    .\scripts\run_integration_tests.ps1
#>
[CmdletBinding()]
param(
    [string]$ContainerName = 'chore-db-integration-test',
    [int]$HostPort = 27017,
    [string]$Image = 'mongo:8',
    [string]$DbName = 'chore_db_test',
    [string]$TestPath = 'tests/test_mongo_adapter.py'
)

$ErrorActionPreference = 'Stop'

$mongoUri = "mongodb://localhost:${HostPort}/${DbName}"

function Test-ContainerRunning {
    $containers = docker ps --filter "name=$ContainerName" --format '{{.Names}}' 2>$null
    return $containers -contains $ContainerName
}

function Wait-MongoReady {
    param([int]$TimeoutSeconds = 30)
    $start = Get-Date
    while (((Get-Date) - $start).TotalSeconds -lt $TimeoutSeconds) {
        try {
            $null = docker exec $ContainerName mongosh --eval 'db.adminCommand({ ping: 1 })' --quiet 2>$null
            if ($LASTEXITCODE -eq 0) {
                return
            }
        } catch {
            # Container or mongosh may not be ready yet.
        }
        Start-Sleep -Seconds 1
    }
    throw "MongoDB container did not become ready within ${TimeoutSeconds} seconds."
}

# Clean up any leftover container from a previous aborted run.
if (Test-ContainerRunning) {
    Write-Host "Removing existing container '$ContainerName'..."
    docker rm -f $ContainerName | Out-Null
}

Write-Host "Starting MongoDB container '$ContainerName' on port $HostPort..."
docker run -d `
    --name $ContainerName `
    -p "${HostPort}:27017" `
    $Image | Out-Null

try {
    Wait-MongoReady
    Write-Host "MongoDB is ready. Running integration tests..."

    $env:USE_MONGODB = 'true'
    $env:MONGO_URI = $mongoUri
    $env:MONGO_DB_NAME = $DbName
    $env:DB_ENV = 'test'
    $env:DATA_ENV = 'test'

    pytest $TestPath
    if ($LASTEXITCODE -ne 0) {
        throw "Integration tests failed with exit code $LASTEXITCODE."
    }
} finally {
    Write-Host "Stopping and removing container '$ContainerName'..."
    docker rm -f $ContainerName | Out-Null
}

Write-Host "Integration tests complete."
