#!/bin/bash
# =============================================================================
# Vihar Sewa deploy script - run on kreonAI5 as the `vihar` OS user.
#
# Usage:
#   sudo -u vihar /www/wwwroot/vihar/deploy/deploy.sh
#
# Steps:
#   1. git pull
#   2. pnpm install
#   3. pnpm db:generate (Prisma client regen)
#   4. pnpm db:migrate:deploy (runs migrations)
#   5. pnpm build (web + api)
#   6. pm2 reload all (zero-downtime)
# =============================================================================

set -euo pipefail

REPO_DIR="/www/wwwroot/vihar"
LOG_DIR="/var/log/vihar"
LOG_FILE="$LOG_DIR/deploy-$(date +%Y%m%d-%H%M%S).log"

mkdir -p "$LOG_DIR"
exec > >(tee "$LOG_FILE") 2>&1

echo "============================================================"
echo "Vihar Sewa deploy - $(date -Iseconds)"
echo "============================================================"

cd "$REPO_DIR"

echo ""
echo "→ Pulling latest from main..."
git fetch --prune
git reset --hard origin/main

echo ""
echo "→ Installing dependencies..."
pnpm install --frozen-lockfile --prod=false

echo ""
echo "→ Generating Prisma client..."
pnpm db:generate

echo ""
echo "→ Running migrations (deploy mode, no prompts)..."
pnpm --filter @vihar/db prisma:migrate:deploy

echo ""
echo "→ Building shared package..."
pnpm --filter @vihar/shared build

echo ""
echo "→ Building API..."
pnpm --filter @vihar/api build

echo ""
echo "→ Building web..."
pnpm --filter @vihar/web build

echo ""
echo "→ Reloading PM2 (zero-downtime)..."
pm2 reload ecosystem.config.js --update-env

echo ""
echo "→ Health check..."
sleep 3
HEALTH=$(curl -sS http://127.0.0.1:4001/health || echo "FAIL")
echo "  API: $HEALTH"
WEB=$(curl -sS -o /dev/null -w "%{http_code}" http://127.0.0.1:3001/ || echo "FAIL")
echo "  Web: HTTP $WEB"

if [[ "$HEALTH" == *"ok"* ]] && [[ "$WEB" == "200" || "$WEB" == "307" ]]; then
  echo ""
  echo "✅ Deploy successful"
  exit 0
else
  echo ""
  echo "❌ Health check failed - investigate immediately"
  echo "   pm2 logs vihar-api --lines 50"
  echo "   pm2 logs vihar-web --lines 50"
  exit 1
fi
