#!/bin/bash
# ============================================
# BDW COOPERATIVE - DEPLOYMENT SCRIPT
# Automated deployment for Replit / VPS
# ============================================

set -e  # Exit on error

echo "🚀 Starting BDW Cooperative Deployment..."
echo "========================================"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
APP_NAME="bdw-cooperative"
APP_DIR="/var/www/behinddwheel.com"
BACKUP_DIR="/backups/bdw"
DEPLOY_DATE=$(date +%Y%m%d_%H%M%S)
NODE_ENV="production"

# ============================================
# 1. PRE-DEPLOYMENT CHECKS
# ============================================
echo -e "${YELLOW}[1/8] Running pre-deployment checks...${NC}"

# Check Node.js version
NODE_VERSION=$(node -v 2>/dev/null || echo "none")
echo "   Node.js version: $NODE_VERSION"

if [[ "$NODE_VERSION" == "none" ]]; then
    echo -e "${RED}❌ Node.js is not installed${NC}"
    exit 1
fi

# Check MySQL
if ! command -v mysql &> /dev/null; then
    echo -e "${RED}❌ MySQL client is not installed${NC}"
    exit 1
fi
echo "   ✅ MySQL client found"

# Check PM2
if ! command -v pm2 &> /dev/null; then
    echo -e "${YELLOW}⚠️  PM2 not found. Installing...${NC}"
    npm install -g pm2
fi
echo "   ✅ PM2 found"

# ============================================
# 2. BACKUP DATABASE
# ============================================
echo -e "${YELLOW}[2/8] Creating database backup...${NC}"

mkdir -p "$BACKUP_DIR"
BACKUP_FILE="$BACKUP_DIR/backup_$DEPLOY_DATE.sql"

if mysqldump -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" > "$BACKUP_FILE" 2>/dev/null; then
    echo -e "   ${GREEN}✅ Database backed up to: $BACKUP_FILE${NC}"
    gzip "$BACKUP_FILE"
    echo "   Compressed: ${BACKUP_FILE}.gz"
else
    echo -e "${RED}❌ Database backup failed${NC}"
    exit 1
fi

# ============================================
# 3. PULL LATEST CODE (or copy from build)
# ============================================
echo -e "${YELLOW}[3/8] Updating application code...${NC}"

if [ -d ".git" ]; then
    # Git-based deployment
    echo "   Pulling latest changes..."
    git pull origin main
    echo -e "   ${GREEN}✅ Code updated from git${NC}"
else
    # Replit/manual deployment
    echo "   Copying from build directory..."
    # (Replit handles this automatically)
    echo -e "   ${GREEN}✅ Using current build${NC}"
fi

# ============================================
# 4. INSTALL DEPENDENCIES
# ============================================
echo -e "${YELLOW}[4/8] Installing dependencies...${NC}"

cd "$APP_DIR/server"

# Clean install for production
rm -rf node_modules package-lock.json
npm ci --production --no-audit --no-fund

echo -e "   ${GREEN}✅ Dependencies installed${NC}"

# ============================================
# 5. RUN DATABASE MIGRATIONS
# ============================================
echo -e "${YELLOW}[5/8] Running database migrations...${NC}"

node database/migrate.js

if [ $? -eq 0 ]; then
    echo -e "   ${GREEN}✅ Migrations completed${NC}"
else
    echo -e "${RED}❌ Migration failed${NC}"
    exit 1
fi

# ============================================
# 6. BUILD FRONTEND ASSETS (if applicable)
# ============================================
echo -e "${YELLOW}[6/8] Building frontend assets...${NC}"

# For static sites, just ensure files are in place
if [ -d "../client" ]; then
    echo "   Client files found"
    # Run any build steps here (e.g., minification)
    echo -e "   ${GREEN}✅ Frontend ready${NC}"
else
    echo "   No client build needed"
fi

# ============================================
# 7. RESTART APPLICATION
# ============================================
echo -e "${YELLOW}[7/8] Restarting application...${NC}"

# Check if app is already running
if pm2 list | grep -q "$APP_NAME"; then
    echo "   Gracefully reloading existing processes..."
    pm2 reload ecosystem.config.js --env production
else
    echo "   Starting application for the first time..."
    pm2 start ecosystem.config.js --env production
fi

# Wait for app to be ready
sleep 3

# Check if app is running
if pm2 list | grep -q "$APP_NAME.*online"; then
    echo -e "   ${GREEN}✅ Application is running${NC}"
else
    echo -e "${RED}❌ Application failed to start${NC}"
    pm2 logs "$APP_NAME" --nostream --lines 20
    exit 1
fi

# ============================================
# 8. POST-DEPLOYMENT VERIFICATION
# ============================================
echo -e "${YELLOW}[8/8] Running post-deployment checks...${NC}"

# Health check
HEALTH_URL="https://behinddwheel.com/api/health"
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$HEALTH_URL" 2>/dev/null || echo "000")

if [ "$HTTP_STATUS" = "200" ]; then
    echo -e "   ${GREEN}✅ Health check passed ($HTTP_STATUS)${NC}"
else
    echo -e "${RED}❌ Health check failed (HTTP $HTTP_STATUS)${NC}"
fi

# Save PM2 process list for restart on reboot
pm2 save

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}   🎉 DEPLOYMENT COMPLETE!              ${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "   📅 Deployed at: $(date)"
echo "   🌍 URL: https://behinddwheel.com"
echo "   ❤️  Health: https://behinddwheel.com/api/health"
echo "   📊 PM2: pm2 status"
echo "   📋 Logs: pm2 logs $APP_NAME"
echo ""
echo -e "${YELLOW}   Backup saved to: ${BACKUP_FILE}.gz${NC}"
echo ""