# Create or verify Ninja Nexus Coolify project and core services.
# Reads: COOLIFY_API_TOKEN, COOLIFY_BASE_URL, COOLIFY_SERVER_ID, NEXUS_DOMAIN
# Never prints secrets.
param(
    [switch]$Json,
    [switch]$DryRun
)

$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "_lib\CoolifyApi.ps1")
Initialize-CoolifyEnv -AllowSecretScript

$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$report = [ordered]@{
    scope       = "create_nexus_project"
    dryRun      = [bool]$DryRun
    domain      = $env:NEXUS_DOMAIN
    serverId    = $env:COOLIFY_SERVER_ID
    project     = $null
    database    = $null
    backend     = $null
    downloads   = $null
    manualSteps = @()
}

try {
    $version = Invoke-CoolifyApi -Method Get -Path "/api/v1/version"
    $report.coolifyVersion = $version.version
} catch {
    throw "Coolify API unreachable: $($_.Exception.Message)"
}

$project = Get-CoolifyProjectByName -Name "Ninja Nexus"
if (-not $project) {
    if ($DryRun) {
        $report.project = @{ action = "would_create"; name = "Ninja Nexus" }
    } else {
        $created = Invoke-CoolifyApi -Method Post -Path "/api/v1/projects" -Body @{
            name        = "Ninja Nexus"
            description = "Ninja Nexus POC — backend, database, downloads"
        }
        $project = Get-CoolifyProjectByName -Name "Ninja Nexus"
        $report.project = @{ action = "created"; uuid = $project.uuid }
    }
} else {
    $report.project = @{ action = "exists"; uuid = $project.uuid }
}

$envName = "production"

$db = Get-CoolifyDatabaseByName -Name "nexus-db"
if (-not $db) {
    if ($DryRun) {
        $report.database = @{ action = "would_create"; name = "nexus-db" }
    } else {
        $dbPassword = New-RandomBase64Key -Bytes 18
        $createdDb = Invoke-CoolifyApi -Method Post -Path "/api/v1/databases/postgresql" -Body @{
            name               = "nexus-db"
            description        = "Ninja Nexus PostgreSQL"
            project_uuid       = $project.uuid
            server_uuid        = $env:COOLIFY_SERVER_ID
            environment_name   = $envName
            postgres_user      = "nexus"
            postgres_password  = $dbPassword
            postgres_db        = "nexus"
        }
        $db = Get-CoolifyDatabaseByName -Name "nexus-db"
        $report.database = @{
            action = "created"
            uuid   = $db.uuid
            status = $db.status
        }
        $report.databasePasswordGenerated = $true
    }
} else {
    $report.database = @{ action = "exists"; uuid = $db.uuid; status = $db.status }
}

$backend = Get-CoolifyApplicationByName -Name "nexus-backend"
if (-not $backend) {
    $dockerfilePath = Join-Path $repoRoot "deployment\coolify\nexus-backend\Dockerfile"
    if (-not (Test-Path $dockerfilePath)) { throw "Missing $dockerfilePath" }

    if ($DryRun) {
        $report.backend = @{ action = "would_create"; name = "nexus-backend" }
    } else {
        $createdApp = Invoke-CoolifyApi -Method Post -Path "/api/v1/applications/dockerfile" -Body @{
            project_uuid       = $project.uuid
            server_uuid        = $env:COOLIFY_SERVER_ID
            environment_name   = $envName
            name               = "nexus-backend"
            description        = "Ninja Nexus ASP.NET Core API"
            dockerfile         = (ConvertTo-Base64Dockerfile -Path $dockerfilePath)
            ports_exposes      = "8080"
            instant_deploy     = $false
        }
        $backend = Get-CoolifyApplicationByName -Name "nexus-backend"
        $report.backend = @{ action = "created"; uuid = $backend.uuid; status = $backend.status }
    }
} else {
    $report.backend = @{ action = "exists"; uuid = $backend.uuid; status = $backend.status }
}

$downloads = Get-CoolifyApplicationByName -Name "nexus-downloads"
if ($downloads) {
    $report.downloads = @{
        action = "exists"
        uuid   = $downloads.uuid
        fqdn   = $downloads.fqdn
        status = $downloads.status
    }
} else {
    $report.downloads = @{ action = "missing" }
    $report.manualSteps += "Create nexus-downloads app manually or run deploy-nexus-downloads.ps1 after first deploy."
}

if (-not $DryRun -and $db -and $backend) {
    try {
        Invoke-CoolifyApi -Method Post -Path "/api/v1/databases/$($db.uuid)/start" -Body @{} | Out-Null
    } catch { }

    if ($db.status -match "exited|unhealthy") {
        $report.manualSteps += "nexus-db is not healthy — open Coolify UI, inspect logs, and restart nexus-db before backend deploy."
    }
}

$report.note = "POC credentials are seeded only when NEXUS_SEED_POC_USERS=true on backend."

if ($Json) { $report | ConvertTo-Json -Depth 6 } else { $report | Format-List }
return $report
