#!/bin/bash

# La Tarte PM2 Startup Script
# This script builds and starts the Next.js application using PM2

set -e

echo "🚀 Starting La Tarte Client with PM2..."

# Step 1: Create logs directory
echo "📁 Creating logs directory..."
mkdir -p logs

# Step 2: Stop any existing PM2 process
echo "🛑 Stopping existing PM2 processes..."
pm2 stop la-tarte-client 2>/dev/null || echo "No existing process to stop"
pm2 delete la-tarte-client 2>/dev/null || echo "No existing process to delete"

# Step 3: Install dependencies (production only)
echo "📦 Installing production dependencies..."
npm ci --only=production

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

# Step 5: Start with PM2
echo "🚀 Starting application with PM2..."
pm2 start ecosystem.config.js --env production

# Step 6: Save PM2 configuration
echo "💾 Saving PM2 configuration..."
pm2 save

# Step 7: Setup PM2 startup script (run once)
echo "⚙️  Setting up PM2 startup script..."
pm2 startup

# Step 8: Show status
echo "📊 PM2 Status:"
pm2 status

echo ""
echo "✅ La Tarte Client is now running with PM2!"
echo "📊 Monitor with: pm2 monit"
echo "📋 View logs with: pm2 logs la-tarte-client"
echo "🔄 Restart with: pm2 restart la-tarte-client"
echo "🛑 Stop with: pm2 stop la-tarte-client"
