#!/usr/bin/env bash
# Production deploy: build TypeScript, run migrations, reload PM2.
set -euo pipefail

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

PM2_APP_NAME="${PM2_APP_NAME:-company-api}"

# Read PORT from .env (Apache .htaccess often proxies to 4200, not 4000)
read_port() {
  if [[ -f .env ]]; then
    local line val
    line="$(grep -E '^[[:space:]]*PORT=' .env | tail -1 || true)"
    val="$(echo "$line" | cut -d= -f2- | tr -d '\r"'"'"' ' | xargs)"
    if [[ -n "$val" ]]; then
      echo "$val"
      return
    fi
  fi
  echo "${PORT:-4000}"
}

APP_PORT="$(read_port)"

if [[ "${SKIP_NPM_CI:-0}" != "1" ]]; then
  echo ">> npm ci --omit=dev"
  npm ci --omit=dev
fi

echo ">> Build (install dev deps for tsc, then prune)"
npm ci
npm run build
npm ci --omit=dev

if [[ ! -f dist/index.js ]]; then
  echo "ERROR: dist/index.js missing after build"
  exit 1
fi

echo ">> Run migrations"
node dist/db/migrate.js

echo ">> Run pending seeds"
node dist/db/seed.js

echo ">> PM2 reload API + email workers (ecosystem.config.cjs)"
if [[ -f ecosystem.config.cjs ]]; then
  pm2 startOrReload ecosystem.config.cjs --update-env
  pm2 save 2>/dev/null || true
elif pm2 describe "${PM2_APP_NAME}" >/dev/null 2>&1; then
  pm2 reload "${PM2_APP_NAME}" --update-env
else
  pm2 start dist/index.js --name "${PM2_APP_NAME}" --cwd "${ROOT}"
fi

echo ">> Local health check on http://127.0.0.1:${APP_PORT}/health"
health_ok=0
for attempt in $(seq 1 30); do
  if curl -sf "http://127.0.0.1:${APP_PORT}/health" >/dev/null 2>&1; then
    health_ok=1
    break
  fi
  if [[ "$attempt" -eq 1 ]] || [[ $((attempt % 5)) -eq 0 ]]; then
    echo "   waiting for API (attempt ${attempt}/30)..."
  fi
  sleep 1
done

if [[ "$health_ok" -ne 1 ]]; then
  echo "ERROR: health check failed on port ${APP_PORT}"
  pm2 describe "${PM2_APP_NAME}" 2>/dev/null || true
  pm2 logs "${PM2_APP_NAME}" --lines 40 --nostream 2>/dev/null || true
  exit 1
fi

curl -sf "http://127.0.0.1:${APP_PORT}/health" | head -c 200
echo ""
echo ">> Post-deploy complete"

if [[ -f scripts/setup-inbound-pipe.sh ]]; then
  echo ">> Inbound pipe (optional)"
  chmod +x scripts/setup-inbound-pipe.sh
  bash scripts/setup-inbound-pipe.sh || echo "WARN: inbound pipe setup failed (see above)"
fi
