# Run both Nexus Coolify deploy steps with visible progress.
param(
    [switch]$DryRun,
    [switch]$SkipBuild,
    [string]$BackendHost = ""
)

$ErrorActionPreference = "Stop"
$here = $PSScriptRoot

Write-Host ""
Write-Host "Ninja Nexus — Coolify deploy (backend + downloads gateway)" -ForegroundColor Cyan
Write-Host "Run from an open PowerShell window (do not double-click .ps1 files)." -ForegroundColor DarkGray
Write-Host ""

$secretScript = Join-Path $env:USERPROFILE ".renninja-secrets\coolify-api-token.ps1"
if (-not (Test-Path $secretScript)) {
    throw "Missing $secretScript — Coolify token must be loaded before deploy."
}
. $secretScript
if (-not $env:COOLIFY_BASE_URL -and $env:COOLIFY_API_BASE_URL) {
    $env:COOLIFY_BASE_URL = $env:COOLIFY_API_BASE_URL
}

$backendParams = @{}
if ($DryRun) { $backendParams.DryRun = $true }
if ($SkipBuild) { $backendParams.SkipBuild = $true }

$backendReport = & (Join-Path $here "deploy-nexus-backend.ps1") @backendParams

if ($DryRun) {
    & (Join-Path $here "deploy-nexus-downloads.ps1") -DryRun -BackendHost $BackendHost | Out-Null
    Write-Host ""
    Write-Host "Dry run OK. Run without -DryRun to deploy for real." -ForegroundColor Yellow
    return $backendReport
}

$sslipHost = if ($BackendHost) {
    $BackendHost
} elseif ($backendReport.backendSslip) {
    ($backendReport.backendSslip -replace '^https?://', '')
} else {
    throw "Backend deploy did not return backendSslip. Pass -BackendHost manually."
}

Write-Host ""
Write-Host "Backend sslip: $sslipHost" -ForegroundColor Green
Write-Host ""

& (Join-Path $here "deploy-nexus-downloads.ps1") -BackendHost $sslipHost

Write-Host ""
Write-Host "Done. Verify:" -ForegroundColor Green
Write-Host "  https://nexus.ninjakernen.info/health" -ForegroundColor DarkGray
Write-Host "  https://nexus.ninjakernen.info/downloads/latest.json" -ForegroundColor DarkGray
