# DBAOps Sovereign™ — One-shot Windows bootstrap
# Prerequisites (winget) + npm run setup + optional start.
# Run from anywhere:  powershell -ExecutionPolicy Bypass -File .\scripts\bootstrap-all.ps1
# Or from repo root:  .\scripts\bootstrap-all.ps1

param(
    [switch]$SkipPrerequisites,
    [switch]$IncludeDocker,
    [switch]$IncludePowerShell7,
    [switch]$IncludeGit,
    [switch]$IncludeSqlExpress,
    [switch]$Start,
    [switch]$WhatIf
)

$ErrorActionPreference = "Stop"
$root = (Get-Item $PSScriptRoot).Parent.FullName
Set-Location $root

Write-Host ""
Write-Host "DBAOps Sovereign™ — bootstrap-all" -ForegroundColor Cyan
Write-Host "Repository: $root" -ForegroundColor Gray
Write-Host ""

if (-not $SkipPrerequisites) {
    $req = Join-Path $PSScriptRoot "install-requirements.ps1"
    $reqArgs = @()
    if ($IncludeDocker) { $reqArgs += "-IncludeDocker" }
    if ($IncludePowerShell7) { $reqArgs += "-IncludePowerShell7" }
    if ($IncludeGit) { $reqArgs += "-IncludeGit" }
    if ($IncludeSqlExpress) { $reqArgs += "-IncludeSqlExpress" }
    if ($WhatIf) { $reqArgs += "-WhatIf" }
    Write-Host ">>> OS prerequisites (winget)…" -ForegroundColor Yellow
    & $req @reqArgs
    Write-Host ""
}

if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
    Write-Host "Node.js is not on PATH. If winget just installed it, close this window, open a new PowerShell, and run this script again with -SkipPrerequisites." -ForegroundColor Red
    Write-Host "Or install from https://nodejs.org/" -ForegroundColor Yellow
    exit 1
}

$maj = 0
try {
    $maj = [int]((node -v) -replace '^v(\d+).*', '$1')
} catch { }
if ($maj -lt 18) {
    Write-Host "Node.js major version is $maj; need 18+. Upgrade Node, then re-run with -SkipPrerequisites." -ForegroundColor Red
    exit 1
}

Write-Host ">>> npm run setup (deps + .env templates)…" -ForegroundColor Yellow
npm run setup
if ($LASTEXITCODE -ne 0) { throw "npm run setup failed" }

Write-Host ""
Write-Host "Bootstrap complete." -ForegroundColor Green

if ($Start) {
    Write-Host ">>> Starting API + dashboard (Ctrl+C to stop)…" -ForegroundColor Yellow
    $env:BROWSER = "none"
    npm start
} else {
    Write-Host "Next steps:" -ForegroundColor Cyan
    Write-Host "  npm start              # dev: API :3041 + UI :3000" -ForegroundColor White
    Write-Host "  .\scripts\run.ps1      # same" -ForegroundColor White
    Write-Host "  npm run docker:up      # full stack in Docker" -ForegroundColor White
    Write-Host "  npm run migrate        # after SQL is configured in .env" -ForegroundColor White
    Write-Host ""
    Write-Host "Open http://localhost:3000 (dashboard) · http://localhost:3041/api/health (API)" -ForegroundColor Gray
}
