#!/bin/bash

# Deployment Script for BCIC Website
# This script helps deploy the application to a server

set -e  # Exit on error

echo "🚀 Starting deployment process..."

# Check if .env.production exists
if [ ! -f .env.production ]; then
    echo "⚠️  Warning: .env.production not found"
    echo "📝 Please create .env.production with your environment variables"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Load environment variables from .env.production if it exists
if [ -f .env.production ]; then
    echo "📦 Loading environment variables from .env.production..."
    export $(cat .env.production | grep -v '^#' | xargs)
fi

# Set production environment
export NODE_ENV=production

# Install dependencies
echo "📥 Installing dependencies..."
npm ci --production

# Build the application
echo "🔨 Building application..."
npm run build

# Check if PM2 is installed
if command -v pm2 &> /dev/null; then
    echo "✅ PM2 detected"
    
    # Check if app is already running
    if pm2 list | grep -q "bcic-website"; then
        echo "🔄 Restarting existing PM2 process..."
        pm2 restart bcic-website
    else
        echo "▶️  Starting new PM2 process..."
        if [ -f ecosystem.config.js ]; then
            pm2 start ecosystem.config.js --env production
        else
            pm2 start npm --name "bcic-website" -- start
        fi
    fi
    
    # Save PM2 configuration
    pm2 save
    
    echo "✅ Deployment complete!"
    echo "📊 View status: pm2 status"
    echo "📋 View logs: pm2 logs bcic-website"
else
    echo "⚠️  PM2 not found. Starting with npm start..."
    echo "💡 Install PM2: npm install -g pm2"
    echo "💡 Then run: pm2 start npm --name 'bcic-website' -- start"
    npm start
fi
