#!/usr/bin/env bash
#
# Run LOCALLY (not on the server). Builds Next.js standalone and creates a
# tarball you can upload to production and unpack there (no npm run build on server).
#
# Usage (from project root):
#   bash scripts/build_nextjs_artifact.sh
#
# Output: nextjs-standalone.tar.gz in project root. Upload it to the server, then run:
#   sudo bash scripts/unpack_and_start_nextjs.sh
#
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
NEXT_DIR="$ROOT/plagis-nextjs"
OUTPUT_TAR="$ROOT/nextjs-standalone.tar.gz"

echo "=============================================="
echo "  Build Next.js artifact for production"
echo "=============================================="
echo ""

if [ ! -d "$NEXT_DIR" ]; then
  echo "Error: $NEXT_DIR not found."
  exit 1
fi

echo "[1/4] Building Next.js (standalone)..."
cd "$NEXT_DIR"
npm ci
npm run build
echo ""

echo "[2/4] Copying .next/static into standalone (required for _next/static/* to work)..."
cp -r .next/static .next/standalone/.next/
echo ""

echo "[3/4] Copying public into standalone..."
cp -r public .next/standalone/public 2>/dev/null || true
echo ""

echo "[4/4] Creating tarball..."
cd "$NEXT_DIR"
tar -czvf "$OUTPUT_TAR" .next/standalone
echo ""
echo "Created: $OUTPUT_TAR"
echo ""
echo "Next: upload this file to the server, then on the server run:"
echo "  sudo bash scripts/unpack_and_start_nextjs.sh"
echo "  (or put the tarball path as first argument if not in project root)"
