#!/bin/bash

echo "=== Anna Stockroom Production Deployment ==="
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo "ERROR: .env file not found!"
    echo "Copy .env.production to .env and configure it first."
    exit 1
fi

# Check if NODE_ENV is production
if ! grep -q "NODE_ENV=production" .env; then
    echo "WARNING: NODE_ENV is not set to production in .env"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Create necessary directories
echo "Creating directories..."
mkdir -p logs uploads

# Install dependencies
echo "Installing dependencies..."
npm ci --production

# Create database indexes
echo "Creating database indexes..."
node scripts/createIndexes.js

# Stop existing PM2 process
echo "Stopping existing process..."
pm2 stop anna-stockroom 2>/dev/null || true

# Start application
echo "Starting application..."
pm2 start ecosystem.config.js --env production

# Save PM2 configuration
pm2 save

# Display status
echo ""
echo "=== Deployment Complete ==="
pm2 status
echo ""
echo "View logs: pm2 logs anna-stockroom"
echo "Monitor: pm2 monit"
echo ""
