#!/bin/bash

# Deployment script for aibitadmin.aibitsoft.cloud
# This script ensures safe deployment without affecting other projects

set -e  # Exit on error

echo "🚀 Starting deployment for aibitadmin.aibitsoft.cloud..."
echo ""

# Get the project directory
PROJECT_DIR="/home/aibitsofts/public_html/aibitadmin.aibitsoft.cloud"
cd "$PROJECT_DIR"

echo "📁 Current directory: $(pwd)"
echo ""

# Check if .env exists
if [ ! -f ".env" ]; then
    echo "⚠️  Warning: .env file not found!"
    echo "   Please create .env file from .env.example"
    echo "   cp .env.example .env"
    echo "   Then edit .env with your production values"
    echo ""
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Install dependencies
echo "📦 Installing dependencies..."
npm install --production

# Build the application
echo "🔨 Building application..."
npm run build

# Create logs directory if it doesn't exist
echo "📝 Creating logs directory..."
mkdir -p logs

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

# Stop existing PM2 process if running
echo "🛑 Stopping existing PM2 process (if running)..."
pm2 stop aibitadmin-backend 2>/dev/null || true
pm2 delete aibitadmin-backend 2>/dev/null || true

# Start with PM2
echo "▶️  Starting application with PM2..."
pm2 start ecosystem.config.js

# Save PM2 configuration
echo "💾 Saving PM2 configuration..."
pm2 save

# Show status
echo ""
echo "✅ Deployment completed!"
echo ""
echo "📊 PM2 Status:"
pm2 status

echo ""
echo "📋 Useful commands:"
echo "   View logs:        pm2 logs aibitadmin-backend"
echo "   Restart:          pm2 restart aibitadmin-backend"
echo "   Stop:             pm2 stop aibitadmin-backend"
echo "   Monitor:          pm2 monit"
echo ""
echo "🌐 Test the API:"
echo "   curl http://localhost:4000/api/health"
echo ""
