#!/usr/bin/env bash
#
# Run on the production server after git pull to build Next.js and restart the service.
# This fixes 502 Bad Gateway when the Next.js app isn't running or standalone is missing.
#
# Usage (from project root on server):
#   cd /var/www/boundary-fastapiandnextjs
#   sudo bash scripts/deploy_nextjs_production.sh
#
set -e

APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
NEXT_DIR="$APP_ROOT/plagis-nextjs"

echo "=============================================="
echo "  Deploy Next.js (build + standalone + restart)"
echo "=============================================="
echo ""

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

echo "[1/5] Installing dependencies..."
cd "$NEXT_DIR"
npm ci
echo ""

echo "[2/5] Building Next.js (production standalone)..."
npm run build
echo ""

echo "[3/5] Copying .next/static into standalone..."
cp -r .next/static .next/standalone/.next/
echo ""

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

echo "[5/5] Installing systemd unit and restarting nextjs..."
cp "$APP_ROOT/scripts/nextjs.service" /etc/systemd/system/nextjs.service
systemctl daemon-reload
systemctl restart nextjs
echo ""

echo "Checking status..."
sleep 2
if systemctl is-active --quiet nextjs; then
  echo "  nextjs: running"
  curl -sS -o /dev/null -w "  HTTP 127.0.0.1:3000 → %{http_code}\n" --connect-timeout 3 http://127.0.0.1:3000/ || true
else
  echo "  nextjs: failed to start. Run: journalctl -u nextjs -n 50 --no-pager"
  exit 1
fi
echo ""
echo "Done. Test the site in the browser."
