# Apply SQL migrations to PostgreSQL (Docker Compose service "postgres").
# See scripts/migrate.sh for behavior (skips 000001_* unless MIGRATE_INCLUDE_BOOTSTRAP=1 or -Bootstrap).

param([switch]$Bootstrap)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$MigrationsDir = Join-Path $Root "backend/migrations"
$ComposeFile = if ($env:COMPOSE_FILE) { $env:COMPOSE_FILE } else { Join-Path $Root "docker-compose.yml" }

$DbUser = if ($env:DB_USER) { $env:DB_USER } else { "autohero" }
$DbName = if ($env:DB_NAME) { $env:DB_NAME } else { "autohero" }
$includeBootstrap = $Bootstrap -or ($env:MIGRATE_INCLUDE_BOOTSTRAP -eq "1")

Set-Location $Root

docker compose -f $ComposeFile exec -T postgres pg_isready -U $DbUser -d $DbName 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Error "postgres is not ready or container is not running. Start: docker compose up -d postgres"
}

Get-ChildItem -Path $MigrationsDir -Filter "*.sql" | Sort-Object Name | ForEach-Object {
    $name = $_.Name
    if ($name -match '^000001_' -and -not $includeBootstrap) {
        Write-Host "Skipping $name (set `$env:MIGRATE_INCLUDE_BOOTSTRAP='1' to apply bootstrap on an empty DB)"
        return
    }
    Write-Host "Applying $name..."
    Get-Content -LiteralPath $_.FullName -Raw | docker compose -f $ComposeFile exec -T postgres `
        psql -v ON_ERROR_STOP=1 -U $DbUser -d $DbName
}

Write-Host "Done."
