#!/usr/bin/env bash
# Production deploy script for sanad-dashboard.
# Run from the project root on the WHM server:
#   bash deploy.sh
# or make it executable once:  chmod +x deploy.sh   then:  ./deploy.sh

set -euo pipefail

APP_NAME="sanad-dashboard"
PORT="3992"

cd "$(dirname "$0")"

echo "==> [1/6] Pulling latest code on branch $(git rev-parse --abbrev-ref HEAD)"
git pull

echo "==> [2/6] Wiping old build artifacts (.next)"
rm -rf .next

echo "==> [3/6] Installing dependencies (npm ci if lockfile present, else npm install)"
if [ -f package-lock.json ]; then
  npm ci --no-audit --no-fund
else
  npm install --no-audit --no-fund
fi

echo "==> [4/6] Building Next.js production bundle"
npm run build

echo "==> [5/6] Restarting PM2 process '$APP_NAME'"
if pm2 describe "$APP_NAME" >/dev/null 2>&1; then
  # Kill ALL processes registered under this name (handles accidental duplicates)
  while pm2 describe "$APP_NAME" >/dev/null 2>&1; do
    pm2 delete "$APP_NAME" || break
  done
fi

# Make sure the port is free before starting fresh
if command -v fuser >/dev/null 2>&1; then
  fuser -k "${PORT}/tcp" 2>/dev/null || true
fi

pm2 start "npm start" --name "$APP_NAME" --update-env
pm2 save

echo "==> [6/6] Verifying"
pm2 list | grep "$APP_NAME" || true
sleep 2
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${PORT}/" || echo "000")
echo "Local health check (http://127.0.0.1:${PORT}/): HTTP $STATUS"

if [ "$STATUS" = "200" ] || [ "$STATUS" = "307" ] || [ "$STATUS" = "302" ]; then
  echo ""
  echo "Deploy complete. Hard-refresh the browser in Incognito to bypass cached chunks."
else
  echo ""
  echo "WARNING: Local health check returned $STATUS. Check 'pm2 logs $APP_NAME --lines 50'."
  exit 1
fi
