#!/usr/bin/env bash
#
# Production Deployment Script
# Déploie les apps web + api sur le VPS
#

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
  echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
  echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
  echo -e "${RED}[ERROR]${NC} $1"
}

# Configuration
VPS_HOST="vps-4d8abcb7"
VPS_USER="myroadtrip"
REPO_PATH="/srv/myroadtrip/repo"
API_SERVICE="myroadtrip-api"
WEB_SERVICE="myroadtrip-web"

log_info "🚀 Starting production deployment..."

# Étape 1: Git pull + install
log_info "📦 Step 1/5: Fetching latest code..."
ssh -t ubuntu@${VPS_HOST} "sudo -u ${VPS_USER} bash -lc '
  set -e
  cd ${REPO_PATH}
  
  # Fetch and pull
  git fetch origin
  git checkout main
  git pull --ff-only origin main
  
  # Clean install (force fresh)
  pnpm install --frozen-lockfile
  
  echo \"✓ Code updated and dependencies installed\"
'"

# Étape 2: Build API
log_info "🔨 Step 2/5: Building API..."
ssh -t ubuntu@${VPS_HOST} "sudo -u ${VPS_USER} bash -lc '
  set -e
  cd ${REPO_PATH}
  
  # Clean previous build
  rm -rf apps/api/dist
  
  # Build with tsup (bundler)
  pnpm --filter @my-roadtrip/api build
  
  # Verify output
  if [ ! -f apps/api/dist/server.js ]; then
    echo \"❌ ERROR: apps/api/dist/server.js not found!\"
    echo \"Build output:\"
    ls -lah apps/api/dist/ || echo \"dist/ directory missing\"
    exit 1
  fi
  
  echo \"✓ API built successfully\"
  ls -lh apps/api/dist/server.js
'"

# Étape 3: Build Web
log_info "🎨 Step 3/5: Building Web app..."
ssh -t ubuntu@${VPS_HOST} "sudo -u ${VPS_USER} bash -lc '
  set -e
  cd ${REPO_PATH}
  
  # Clean previous build
  rm -rf apps/web/dist
  
  # Build with Vite
  pnpm --filter @my-roadtrip/web build
  
  # Verify output
  if [ ! -f apps/web/dist/index.html ]; then
    echo \"❌ ERROR: apps/web/dist/index.html not found!\"
    exit 1
  fi
  
  echo \"✓ Web app built successfully\"
  du -sh apps/web/dist/
'"

# Étape 4: Restart services
log_info "🔄 Step 4/5: Restarting services..."
ssh -t ubuntu@${VPS_HOST} "
  # Restart API
  sudo systemctl restart ${API_SERVICE}
  sleep 3
  
  # Check API status
  if ! sudo systemctl is-active --quiet ${API_SERVICE}; then
    echo \"❌ API service failed to start!\"
    sudo journalctl -u ${API_SERVICE} -n 50 --no-pager
    exit 1
  fi
  
  # Restart Web (Nginx reload)
  sudo systemctl reload nginx
  
  echo \"✓ Services restarted\"
"

# Étape 5: Health check
log_info "🏥 Step 5/5: Health check..."
ssh -t ubuntu@${VPS_HOST} "
  # Wait for API to be ready
  sleep 2
  
  # Check API health
  API_STATUS=\$(curl -s -o /dev/null -w '%{http_code}' http://localhost:3000/health || echo '000')
  
  if [ \"\$API_STATUS\" = \"200\" ]; then
    echo \"✓ API health check passed (HTTP 200)\"
  else
    echo \"⚠️  API health check returned HTTP \$API_STATUS\"
  fi
  
  # Check service status
  echo \"\"
  echo \"Service Status:\"
  sudo systemctl status ${API_SERVICE} --no-pager -l | head -10
  
  echo \"\"
  echo \"Recent logs:\"
  sudo journalctl -u ${API_SERVICE} -n 10 --no-pager
"

log_info "✅ Deployment completed!"
log_info ""
log_info "📊 Summary:"
log_info "  - API: https://api./health"
log_info "  - Web: https://"
log_info ""
log_warn "Don't forget to check Sentry for errors: https://sentry.io"
