#!/bin/bash
# Deploy script para Kevin Victor CMS
# Uso: VPS_PASS="tu_password" ./scripts/deploy-cms.sh
#
# Pre-requisitos:
#   - sshpass instalado (brew install sshpass)
#   - Variable de entorno VPS_PASS con la contraseña root del VPS
#   - O configurar SSH key (recomendado) — entonces NO necesitas VPS_PASS

set -euo pipefail

VPS_HOST="162.240.232.251"
VPS_PORT="22022"
VPS_USER="root"
APP_DIR="/var/www/cms.kevinvictorrealestate.com"
APP_NAME="kv-cms"
APP_PORT=3002

# SSH key tiene prioridad; si no, usa VPS_PASS
if [ -z "${VPS_PASS:-}" ] && [ -z "${SSH_KEY_PATH:-}" ]; then
  echo "❌ Error: debes exportar VPS_PASS o SSH_KEY_PATH antes de ejecutar este script."
  echo "   Ejemplos:"
  echo "     VPS_PASS='xxx' ./scripts/deploy-cms.sh"
  echo "     SSH_KEY_PATH=~/.ssh/id_ed25519_kevin ./scripts/deploy-cms.sh"
  exit 1
fi

# SSH args (con o sin IdentityFile)
if [ -n "${SSH_KEY_PATH:-}" ]; then
  SSH_ARGS="-i $SSH_KEY_PATH -o StrictHostKeyChecking=no -p $VPS_PORT"
  RSYNC_SSH="ssh -i $SSH_KEY_PATH -o StrictHostKeyChecking=no -p $VPS_PORT"
else
  SSH_ARGS="-o StrictHostKeyChecking=no -p $VPS_PORT"
  RSYNC_SSH="ssh -o StrictHostKeyChecking=no -p $VPS_PORT"
fi

echo "▶ [1/6] Verificando build local..."
if [ ! -d ".next" ]; then
  echo "  ADVERTENCIA: .next no existe, construyendo..."
  npm ci
  npx prisma generate
  npm run build
else
  echo "  OK .next existe"
fi

echo ""
echo "▶ [2/6] Sync de archivos al VPS (excluye node_modules y .env)..."
if [ -n "${VPS_PASS:-}" ]; then
  SSHPASS="$VPS_PASS" rsync -avz --delete \
    --exclude 'node_modules' \
    --exclude '.next/cache' \
    --exclude '.env*' \
    --exclude '.git' \
    -e "$RSYNC_SSH" \
    ./ "$VPS_USER@$VPS_HOST:$APP_DIR/"
else
  rsync -avz --delete \
    --exclude 'node_modules' \
    --exclude '.next/cache' \
    --exclude '.env*' \
    --exclude '.git' \
    -e "$RSYNC_SSH" \
    ./ "$VPS_USER@$VPS_HOST:$APP_DIR/"
fi

echo ""
echo "▶ [3/6] Instalando deps de produccion en VPS..."
ssh $SSH_ARGS "$VPS_USER@$VPS_HOST" "cd $APP_DIR && npm ci --omit=dev"

echo ""
echo "▶ [4/6] Aplicando migraciones Prisma..."
ssh $SSH_ARGS "$VPS_USER@$VPS_HOST" "cd $APP_DIR && npx prisma migrate deploy"

echo ""
echo "▶ [5/6] Reiniciando proceso PM2 ($APP_NAME)..."
ssh $SSH_ARGS "$VPS_USER@$VPS_HOST" "cd $APP_DIR && (pm2 restart $APP_NAME || pm2 start npm --name $APP_NAME -- start) && pm2 save"

echo ""
echo "▶ [6/6] Verificacion final..."
sleep 3
ssh $SSH_ARGS "$VPS_USER@$VPS_HOST" "pm2 show $APP_NAME | grep -E 'status|uptime' | head -5"

echo ""
echo "OK Deploy completo. Test: https://cms.kevinvictorrealestate.com/login"