#!/bin/bash
########################################
# Queue Depth Monitor
# Alerts when jobs are pending
########################################

# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT" || exit 1

# Load cron context
source "$SCRIPT_DIR/_cron-context.sh" 2>/dev/null || true

# Get pending jobs count from database
PENDING=$(php artisan tinker --execute="echo DB::table('jobs')->count();" 2>/dev/null || echo "0")

# Alert threshold (alert if more than 3 jobs pending)
THRESHOLD=3

# Only alert if above threshold
if [ "$PENDING" -gt "$THRESHOLD" ]; then
    get_cron_context "$PROJECT_ROOT" 2>/dev/null || true
    echo "⚠️  QUEUE DEPTH ALERT"
    echo ""
    echo "Pending Jobs: $PENDING (threshold: $THRESHOLD)"
    echo ""

    # Show job breakdown by queue
    echo "Job Breakdown:"
    php artisan tinker --execute="
        \$jobs = DB::table('jobs')
            ->select('queue', DB::raw('COUNT(*) as count'))
            ->groupBy('queue')
            ->get();
        foreach (\$jobs as \$job) {
            echo \"  {$job->queue}: {$job->count}\n\";
        }
    " 2>/dev/null || echo "  (Unable to fetch breakdown)"
    echo ""

    # Check worker status
    WORKER_PID=$(cat "$PROJECT_ROOT/storage/queue-worker.pid" 2>/dev/null || echo "")
    if [ -n "$WORKER_PID" ] && ps -p "$WORKER_PID" > /dev/null 2>&1; then
        echo "✅ Worker is running (PID: $WORKER_PID)"
        echo "   Jobs may be processing slowly or worker just restarted"
    else
        echo "❌ Worker is NOT running - this is a critical issue!"
    fi
fi

exit 0
