# Deploy Script
param (
    # automatically determine root relative to this script (scripts/ folder)
    [string]$ProjectRoot = (Resolve-Path "$PSScriptRoot/..").Path
)

$ErrorActionPreference = "Stop"
$DockerAppDir = Join-Path $ProjectRoot "dockerapp"
$NextDir = Join-Path $ProjectRoot ".next"
$PublicDir = Join-Path $ProjectRoot "public"
$PrismaDir = Join-Path $ProjectRoot "prisma"

Write-Host "📦 Starting Dockerapp Packaging..." -ForegroundColor Cyan
Write-Host "   Project Root: $ProjectRoot"

# 1. Clean dockerapp (Keep Dockerfile & docker-compose.yml)
Write-Host "   Cleaning previous build artifacts..."
Get-ChildItem -Path $DockerAppDir -Exclude Dockerfile, docker-compose.yml | Remove-Item -Recurse -Force

# 2. Copy Standalone (Exclude node_modules because Dockerfile reinstalls them)
Write-Host "   Copying Standalone build (skipping node_modules)..."
if (!(Test-Path "$NextDir/standalone")) {
    Write-Error "❌ .next/standalone not found! Run 'npm run build' first."
}
# Copy everything inside standalone EXCEPT node_modules
Get-ChildItem -Path "$NextDir/standalone" -Exclude "node_modules" | Copy-Item -Destination $DockerAppDir -Recurse -Force

# 3. Copy Static Assets (Crucial!)
Write-Host "   Copying Static assets..."
$DestStatic = Join-Path $DockerAppDir ".next/static"
New-Item -ItemType Directory -Path $DestStatic -Force | Out-Null
Copy-Item -Path "$NextDir/static/*" -Destination $DestStatic -Recurse -Force

# 4. Copy Public Assets
Write-Host "   Copying Public folder..."
Copy-Item -Path $PublicDir -Destination $DockerAppDir -Recurse -Force

# 5. Copy Prisma
Write-Host "   Copying Prisma..."
Copy-Item -Path $PrismaDir -Destination $DockerAppDir -Recurse -Force

Write-Host "✅ Packaging Complete!" -ForegroundColor Green
Write-Host "   Location: $DockerAppDir"
Write-Host "   Next Step: Upload 'dockerapp' folder to server and run 'docker-compose up -d --build'"
