# Build and deploy Nexus backend to Coolify.
# Uses published tar.gz artifact (ADD in Dockerfile) because Coolify dockerfile apps
# have no git build context. Backend must listen on port 80 (Coolify Traefik default).
param(
    [switch]$Json,
    [switch]$DryRun,
    [switch]$SkipBuild
)

$ErrorActionPreference = "Stop"
Write-Host "=== deploy-nexus-backend ===" -ForegroundColor Cyan
. (Join-Path $PSScriptRoot "_lib\CoolifyApi.ps1")
Initialize-CoolifyEnv -AllowSecretScript

$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$publishDir = Join-Path $repoRoot "dist\nexus-backend-publish"
$tgzPath = Join-Path $repoRoot "dist\nexus-backend-publish.tar.gz"

$report = [ordered]@{
    scope  = "deploy_nexus_backend"
    dryRun = [bool]$DryRun
    domain = $env:NEXUS_DOMAIN
}

function Get-TempFileDownloadUrl {
    param([string]$FilePath)
    $out = Join-Path $env:TEMP ("nexus-backend-upload-" + [Guid]::NewGuid().ToString("N") + ".txt")
    try {
        curl.exe -sS -F "reqtype=fileupload" -F "fileToUpload=@$FilePath" "https://catbox.moe/user/api.php" -o $out
        if ($LASTEXITCODE -eq 0) {
            $url = (Get-Content $out -Raw).Trim()
            if ($url -match '^https?://') { return $url }
        }
    } finally {
        Remove-Item $out -Force -ErrorAction SilentlyContinue
    }
    throw "Temporary upload failed for $(Split-Path $FilePath -Leaf)"
}

if (-not $SkipBuild -and -not $DryRun) {
    Write-Host "Building and packaging backend..." -ForegroundColor Cyan
    if (Test-Path $publishDir) { Remove-Item -LiteralPath $publishDir -Recurse -Force }
    dotnet publish (Join-Path $repoRoot "source\nexus-identity\NexusIdentity.Api\NexusIdentity.Api.csproj") `
        -c Release -o $publishDir --self-contained false
    if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed." }
    if (Test-Path $tgzPath) { Remove-Item -LiteralPath $tgzPath -Force }
    tar -czf $tgzPath -C $publishDir .
    $report.build = "ok"
}

if ($DryRun) {
    $report.deploy = "dry_run"
    $report.note = "Recreates dockerfile app with ADD tar.gz; listens on port 80."
    if ($Json) { $report | ConvertTo-Json -Depth 5 } else { $report | Format-List }
    return $report
}

if (-not (Test-Path $tgzPath)) { throw "Missing $tgzPath. Run without -SkipBuild first." }
$artifactUrl = Get-TempFileDownloadUrl -FilePath $tgzPath
$report.artifactUploaded = $true

$dockerfile = @'
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
ADD ARTIFACT_URL /tmp/publish.tgz
RUN tar -xzf /tmp/publish.tgz -C /app && rm /tmp/publish.tgz
ENV ASPNETCORE_URLS=http://+:80
EXPOSE 80
ENTRYPOINT ["dotnet", "NexusIdentity.Api.dll"]
'@.Replace('ARTIFACT_URL', $artifactUrl)

$project = Get-CoolifyProjectByName -Name "Ninja Nexus"
if (-not $project) { throw "Ninja Nexus project missing. Run create-nexus-project.ps1 first." }

$backend = Get-CoolifyApplicationByName -Name "nexus-backend"
if ($backend) {
    try {
        Invoke-CoolifyApi -Method Delete -Path "/api/v1/applications/$($backend.uuid)" | Out-Null
        $report.previousAppRemoved = $backend.uuid
    } catch {
        $report.previousAppRemoveError = $_.Exception.Message
    }
}

$created = Invoke-CoolifyApi -Method Post -Path "/api/v1/applications/dockerfile" -Body @{
    project_uuid     = $project.uuid
    server_uuid      = $env:COOLIFY_SERVER_ID
    environment_name = "production"
    name             = "nexus-backend"
    description      = "Ninja Nexus ASP.NET Core API"
    dockerfile       = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($dockerfile))
    ports_exposes    = "80"
    instant_deploy   = $true
}

$appUuid = $created.uuid
$report.appUuid = $appUuid
$report.backendSslip = "http://$appUuid.85.208.48.244.sslip.io"

$jwtKey = New-RandomBase64Key -Bytes 48
Set-CoolifyApplicationEnv -AppUuid $appUuid -EnvVars @{
    NEXUS_JWT_SIGNING_KEY    = $jwtKey
    NEXUS_SEED_POC_USERS     = "true"
    NEXUS_DOMAIN             = $env:NEXUS_DOMAIN
    NEXUS_DB_CONNECTION      = "Data Source=/app/nexus.db"
    NEXUS_DOWNLOADS_BASE_URL = "$(Get-NexusDomainUrl)/downloads"
    NEXUS_ENVIRONMENT        = "Production"
}

Write-Host "Waiting for backend deploy (about 2 minutes)..." -ForegroundColor Cyan
for ($i = 1; $i -le 12; $i++) {
    Start-Sleep -Seconds 10
    Write-Host "  ... $($i * 10)s" -ForegroundColor DarkGray
}

$app = Invoke-CoolifyApi -Method Get -Path "/api/v1/applications/$appUuid"
$report.appStatus = $app.status
$report.deploy = "completed"

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