#!/usr/bin/env bash
# Deploy modstagram-next on Ubuntu server (after git pull / upload)
set -euo pipefail

APP_DIR="${APP_DIR:-/root/modstagram-next}"
cd "$APP_DIR"

echo ">>> Node: $(node -v) | npm: $(npm -v)"

if [ ! -f .env.production ] && [ ! -f .env.local ]; then
  echo "WARN: no .env.production — copy .env.production.example and fill values"
fi

echo ">>> npm ci ..."
npm ci

echo ">>> npm run build ..."
npm run build

if [ ! -d .next ]; then
  echo "ERROR: .next missing — build failed"
  exit 1
fi

echo ">>> PM2 — stop old process (may be on port 3004) ..."
pm2 delete modstagram-next 2>/dev/null || true

echo ">>> PM2 start on port 3004 (nginx upstream) ..."
pm2 start ecosystem.config.cjs --update-env
pm2 save

echo ">>> Verify listen ports ..."
ss -tlnp | grep -E '3001|3004' || true

echo ">>> Health check (port 3004) ..."
sleep 3
curl -sf -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:3004/ || {
  echo "ERROR: Next.js not responding on 127.0.0.1:3004"
  pm2 logs modstagram-next --lines 40 --nostream
  exit 1
}

if ss -tlnp | grep -q ':3004'; then
  echo "WARN: something still listens on 3004 — check pm2 list / duplicate processes"
fi

echo ">>> Done. Reload nginx if you changed config:"
echo "    nginx -t && systemctl reload nginx"
