#!/bin/bash

# LuckyChit Backend Deployment Script
# Usage: ./deploy.sh [production|development]

ENV=${1:-production}
APP_NAME="luckychit-backend"

echo "🚀 Deploying LuckyChit Backend - Environment: $ENV"
echo "================================================"

# Check if PM2 is installed
if ! command -v pm2 &> /dev/null; then
    echo "❌ PM2 is not installed. Installing..."
    npm install -g pm2
fi

# Clean install dependencies (fixes native module issues like bcrypt)
echo "📦 Installing dependencies..."
echo "   Cleaning old modules to rebuild native bindings..."
rm -rf node_modules package-lock.json
npm install --production

# Create logs directory if it doesn't exist
if [ ! -d "logs" ]; then
    echo "📁 Creating logs directory..."
    mkdir -p logs
fi

# Check if .env file exists
if [ ! -f ".env" ]; then
    echo "⚠️  Warning: .env file not found!"
    echo "Please create .env file with production credentials"
    echo "Example: cp .env.example .env"
    exit 1
fi

# Stop existing PM2 process if running
if pm2 describe $APP_NAME > /dev/null 2>&1; then
    echo "🛑 Stopping existing process..."
    pm2 delete $APP_NAME
fi

# Start application with PM2
echo "🎯 Starting application with PM2..."
if [ "$ENV" == "production" ]; then
    pm2 start ecosystem.config.js --env production
else
    pm2 start ecosystem.config.js --env development
fi

# Save PM2 process list
echo "💾 Saving PM2 process list..."
pm2 save

# Show status
echo ""
echo "✅ Deployment complete!"
echo ""
pm2 list
echo ""
echo "📊 Monitor with: pm2 monit"
echo "📝 View logs with: pm2 logs $APP_NAME"
echo ""

