#!/bin/bash

# Exit on error
set -e

echo "🚀 Starting deployment..."

# Clear any cached config to ensure fresh environment variables are loaded
echo "🧹 Clearing cached config..."
php artisan config:clear

# Fresh migration and seeding (drops all tables and recreates)
echo "🔥 Running FRESH migration with seeding..."
echo "⚠️  WARNING: This will DELETE ALL existing data!"

#kalo mau database tidak fresh cuma force diaktifin, hapus tanda pagar di baris bawah
# php artisan migrate --force
# php artisan db:seed --class=ProductionSeeder --force

#kalo mau database fresh diaktifin, hapus tanda pagar di baris bawah
php artisan migrate:fresh --seed --force

# Create storage link (ignore if already exists)
echo "🔗 Creating storage link..."
php artisan storage:link || echo "Storage link already exists"

# Optimize application
echo "⚡ Optimizing application..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Railway sets PORT automatically, but if it conflicts with DB port, use a safe default
if [ -z "$PORT" ] || [ "$PORT" = "3306" ] || [ "$PORT" = "5432" ]; then
    export PORT=8080
fi

# ========================================
# Queue Worker Management
# ========================================

# Function to check if queue worker is running
check_queue_worker() {
    if pgrep -f "artisan queue:work" > /dev/null 2>&1; then
        return 0  # Running
    else
        return 1  # Not running
    fi
}

# Function to start queue worker
start_queue_worker() {
    echo "🔄 Starting queue worker..."
    # Run queue worker in background with auto-restart
    # --tries=3: Retry failed jobs 3 times
    # --timeout=90: Each job has 90 seconds max
    # --sleep=3: Sleep 3 seconds when no jobs
    # --max-jobs=1000: Restart worker after 1000 jobs (prevent memory leaks)
    # --max-time=3600: Restart worker every hour (prevent memory leaks)
    nohup php artisan queue:work --tries=3 --timeout=90 --sleep=3 --max-jobs=1000 --max-time=3600 >> /tmp/queue-worker.log 2>&1 &
    QUEUE_PID=$!
    echo "✅ Queue worker started with PID: $QUEUE_PID"
}

# Function to monitor and restart queue worker if crashed
monitor_queue_worker() {
    while true; do
        sleep 60  # Check every 60 seconds
        if ! check_queue_worker; then
            echo "⚠️  Queue worker stopped! Restarting..."
            start_queue_worker
        fi
    done
}

# Clear any failed jobs from previous sessions (optional)
echo "🧹 Clearing old failed jobs..."
php artisan queue:flush 2>/dev/null || echo "No failed jobs to clear"

# Check pending jobs
PENDING_JOBS=$(php artisan queue:monitor database:default --json 2>/dev/null | grep -o '"size":[0-9]*' | grep -o '[0-9]*' || echo "0")
echo "📊 Pending jobs in queue: ${PENDING_JOBS:-0}"

# Start queue worker
start_queue_worker

# Start queue worker monitor in background
monitor_queue_worker &
MONITOR_PID=$!
echo "👀 Queue monitor started with PID: $MONITOR_PID"

# Trap to cleanup background processes on exit
cleanup() {
    echo "🛑 Shutting down..."
    # Kill queue worker and monitor
    pkill -f "artisan queue:work" 2>/dev/null || true
    kill $MONITOR_PID 2>/dev/null || true
    exit 0
}
trap cleanup SIGTERM SIGINT SIGQUIT

# ========================================
# Start Web Server
# ========================================
echo "✅ Starting web server..."
echo "📡 Listening on port: $PORT"
php artisan serve --host=0.0.0.0 --port=$PORT
