#!/usr/bin/env bash
set -e

echo "🚀 Starting deployment..."

# Turn on maintenance mode
php artisan down || true

echo "📥 Pulling latest code..."
git pull origin main

echo "📦 Installing Composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

echo "🗄️ Running database migrations..."
php artisan migrate --force

echo "⚡ Optimizing Laravel application caches..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

echo "🎨 Building frontend assets..."
if [ -f "package.json" ]; then
    npm ci || npm install
    npm run build
fi

echo "🔒 Ensuring correct directory permissions..."
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

echo "🔄 Reloading PM2 processes..."
pm2 reload ecosystem.config.cjs || pm2 start ecosystem.config.cjs

# Turn off maintenance mode
php artisan up

echo "✅ Deployment finished successfully!"
