param(
  [string]$ImageName = "jgjs2026-dist",
  [string]$Tag = "latest"
)

$ErrorActionPreference = "Stop"

$projectRoot = Split-Path -Parent $PSScriptRoot
$distPath = Join-Path $projectRoot "dist"
$dockerfilePath = Join-Path $projectRoot "Dockerfile.dist"
$serverSourcePath = Join-Path $projectRoot "docker\\dist-server"
$buildContext = Join-Path ([System.IO.Path]::GetTempPath()) ("jgjs2026-dist-docker-" + [System.Guid]::NewGuid().ToString("N"))

if (-not (Test-Path $distPath)) {
  throw "dist directory not found. Run npm run build first."
}

if (-not (Test-Path $dockerfilePath)) {
  throw "Dockerfile.dist not found."
}

if (-not (Test-Path $serverSourcePath)) {
  throw "docker/dist-server not found."
}

New-Item -ItemType Directory -Path $buildContext | Out-Null
New-Item -ItemType Directory -Path (Join-Path $buildContext "docker") | Out-Null

try {
  Copy-Item $dockerfilePath (Join-Path $buildContext "Dockerfile.dist")
  Copy-Item $serverSourcePath (Join-Path $buildContext "docker\\dist-server") -Recurse
  Copy-Item $distPath (Join-Path $buildContext "dist") -Recurse

  Write-Host "Building Docker image ${ImageName}:${Tag} from minimal dist context..."
  docker build -f (Join-Path $buildContext "Dockerfile.dist") -t "${ImageName}:${Tag}" $buildContext
}
finally {
  if (Test-Path $buildContext) {
    Remove-Item $buildContext -Recurse -Force
  }
}

Write-Host "Done."
Write-Host "Run with:"
Write-Host "docker run --rm -p 8080:80 ${ImageName}:${Tag}"
