#Requires -Version 5.1
<#
.SYNOPSIS
    Rebuild and redeploy MeshiTrack Docker images.

.PARAMETER Services
    One or more services to rebuild. Defaults to 'api' and 'web'.
    Valid values: api, web

.PARAMETER NoCache
    Pass --no-cache to docker compose build.

.PARAMETER Target
    Build target: 'development' (default) or 'production'.

.EXAMPLE
    .\deploy.ps1
    .\deploy.ps1 -Services api
    .\deploy.ps1 -NoCache
    .\deploy.ps1 -Target production -NoCache
#>
param(
    [ValidateSet('api', 'web')]
    [string[]]$Services = @('api', 'web'),

    [switch]$NoCache,

    [ValidateSet('development', 'production')]
    [string]$Target = 'development'
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$ComposeFile = Join-Path $PSScriptRoot 'docker\docker-compose.yml'

if (-not (Test-Path $ComposeFile)) {
    Write-Error "docker-compose.yml not found at: $ComposeFile"
    exit 1
}

$BuildArgs = @('compose', '-f', $ComposeFile, 'build', '--build-arg', "target=$Target")
if ($NoCache) {
    $BuildArgs += '--no-cache'
}
$BuildArgs += $Services

Write-Host "Building: $($Services -join ', ')  [target=$Target$(if ($NoCache) { ', no-cache' })]"
& docker @BuildArgs
if ($LASTEXITCODE -ne 0) {
    Write-Error "docker compose build failed (exit $LASTEXITCODE)"
    exit $LASTEXITCODE
}

$UpArgs = @('compose', '-f', $ComposeFile, 'up', '-d', '--force-recreate')
$UpArgs += $Services

Write-Host "Deploying: $($Services -join ', ')"
& docker @UpArgs
if ($LASTEXITCODE -ne 0) {
    Write-Error "docker compose up failed (exit $LASTEXITCODE)"
    exit $LASTEXITCODE
}

Write-Host "Done. Running containers:"
& docker compose -f $ComposeFile ps
