#!/usr/bin/env bash
# ---------------------------------------------------------------------------
#  Build + (re)start the support portal on the VPS.
#  Run from the app root:   bash deploy/deploy.sh
# ---------------------------------------------------------------------------
set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$APP_DIR"

echo "==> $APP_DIR"

if [ ! -f .env ]; then
  echo "!! .env is missing. Copy .env.production.example to .env and fill it in." >&2
  exit 1
fi

echo "==> Installing dependencies"
# devDependencies are REQUIRED here: next build needs tailwind/postcss/prisma
if [ -f package-lock.json ]; then npm ci; else npm install; fi

echo "==> Prisma client + schema"
npx prisma generate
npx prisma db push          # creates/updates tables, non-destructive

echo "==> Building"
npm run build

echo "==> Restarting service"
if command -v pm2 >/dev/null 2>&1 && pm2 describe support-portal >/dev/null 2>&1; then
  pm2 reload support-portal --update-env
  pm2 save
elif command -v pm2 >/dev/null 2>&1; then
  pm2 start ecosystem.config.js --env production
  pm2 save
elif systemctl list-unit-files 2>/dev/null | grep -q '^support-portal.service'; then
  sudo systemctl restart support-portal
else
  echo "!! No pm2 process and no systemd unit found — start one first (see DEPLOY.md)." >&2
  exit 1
fi

echo "==> Done. Local check:"
sleep 3
curl -sS -o /dev/null -w "  http://127.0.0.1:${PORT:-3000}/  ->  %{http_code}\n" "http://127.0.0.1:${PORT:-3000}/" || true
