# build-push.ps1 — Build both ROLAC images and push them to the Gitea registry.
#
# Usage (from anywhere):
#   .\deploy\build-push.ps1                  # tags :latest and :<git-sha>
#   .\deploy\build-push.ps1 -Tag v1.2.0      # also adds an extra :v1.2.0 tag
#   .\deploy\build-push.ps1 -NoPush          # build only, don't push
#
# Prereqs:
#   - Docker Desktop running
#   - docker login git.golife.love   (once, with a write:package access token)

param(
    [string]$Tag,            # optional extra tag, e.g. a release version
    [switch]$NoPush          # build only
)

$ErrorActionPreference = 'Stop'

# Repo root = parent of this script's folder
$RepoRoot = Split-Path -Parent $PSScriptRoot
$Registry = 'git.golife.love/chrischen'
$Api      = "$Registry/rolac-api"
$App      = "$Registry/rolac-app"

# Short git sha for an immutable version tag
$Sha = (git -C $RepoRoot rev-parse --short HEAD).Trim()
Write-Host "Building from commit $Sha" -ForegroundColor Cyan

# Assemble the -t arguments for each image
$apiTags = @('-t', "${Api}:latest", '-t', "${Api}:$Sha")
$appTags = @('-t', "${App}:latest", '-t', "${App}:$Sha")
if ($Tag) {
    $apiTags += @('-t', "${Api}:$Tag")
    $appTags += @('-t', "${App}:$Tag")
}

Write-Host "==> Building API image" -ForegroundColor Green
docker build @apiTags "$RepoRoot\API"
if ($LASTEXITCODE -ne 0) { throw "API build failed" }

Write-Host "==> Building APP image" -ForegroundColor Green
docker build @appTags "$RepoRoot\APP"
if ($LASTEXITCODE -ne 0) { throw "APP build failed" }

if ($NoPush) {
    Write-Host "Build complete (push skipped)." -ForegroundColor Yellow
    return
}

Write-Host "==> Pushing API image" -ForegroundColor Green
docker push --all-tags $Api
if ($LASTEXITCODE -ne 0) { throw "API push failed" }

Write-Host "==> Pushing APP image" -ForegroundColor Green
docker push --all-tags $App
if ($LASTEXITCODE -ne 0) { throw "APP push failed" }

Write-Host "Done. Pushed :latest and :$Sha$(if($Tag){" and :$Tag"})." -ForegroundColor Cyan
