#!/usr/bin/env bash
# =============================================================================
# RecreaHUB API — Zero-Downtime Deploy Script
# Run from the application root: bash scripts/deploy.sh
# =============================================================================
set -euo pipefail

TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S %Z')
APP_NAME="recreahub-api"
BRANCH="main"

echo ""
echo "============================================================"
echo "  RecreaHUB API — Deploy"
echo "  Started at: ${TIMESTAMP}"
echo "============================================================"
echo ""

# ── 1. Pull latest code from remote ──────────────────────────────────────────
echo "[1/4] Pulling latest changes from origin/${BRANCH}..."
git pull origin "${BRANCH}"
GIT_HASH=$(git rev-parse --short HEAD)
echo "  HEAD is now at: ${GIT_HASH}"

# ── 2. Install / update production dependencies ──────────────────────────────
echo "[2/4] Installing production dependencies..."
npm install --omit=dev
echo "  Dependencies up to date."

# ── 3. Zero-downtime cluster reload ──────────────────────────────────────────
echo "[3/4] Reloading ${APP_NAME} with zero downtime..."
pm2 reload "${APP_NAME}" --update-env
echo "  Reload complete."

# ── 4. Persist updated process list ──────────────────────────────────────────
echo "[4/4] Saving PM2 process list..."
pm2 save
echo "  Process list saved."

echo ""
echo "============================================================"
echo "  Deploy summary"
echo "  App       : ${APP_NAME}"
echo "  Commit    : ${GIT_HASH}"
echo "  Finished  : $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "  Status    :"
pm2 show "${APP_NAME}" | grep -E 'status|restarts|uptime' || true
echo "============================================================"
