#!/bin/bash
# Check queue statistics
# Usage: ./queue-stats.sh

cd /var/www/html/profileCustomizerGHL

echo "════════════════════════════════════════════════════════"
echo "📊 QUEUE STATISTICS"
echo "════════════════════════════════════════════════════════"
echo ""

# Get database queue stats
php artisan tinker --execute="
echo '📦 Jobs in Queue:' . PHP_EOL;
echo '  Pending: ' . \DB::table('jobs')->count() . PHP_EOL;
echo '  Failed: ' . \DB::table('failed_jobs')->count() . PHP_EOL;
echo PHP_EOL;

\$pending = \DB::table('jobs')->count();
if (\$pending > 0) {
    echo '⏳ Pending Jobs Details:' . PHP_EOL;
    \DB::table('jobs')->orderBy('created_at', 'desc')->take(10)->get(['id', 'queue', 'attempts', 'created_at'])->each(function(\$job) {
        echo '  - ID: ' . \$job->id . ' | Queue: ' . \$job->queue . ' | Attempts: ' . \$job->attempts . ' | Created: ' . \$job->created_at . PHP_EOL;
    });
    echo PHP_EOL;
}

\$failed = \DB::table('failed_jobs')->count();
if (\$failed > 0) {
    echo '❌ Failed Jobs (Last 5):' . PHP_EOL;
    \DB::table('failed_jobs')->orderBy('failed_at', 'desc')->take(5)->get(['id', 'queue', 'exception', 'failed_at'])->each(function(\$job) {
        \$exception = substr(\$job->exception, 0, 100);
        echo '  - ID: ' . \$job->id . ' | Queue: ' . \$job->queue . PHP_EOL;
        echo '    Error: ' . \$exception . '...' . PHP_EOL;
        echo '    Failed: ' . \$job->failed_at . PHP_EOL;
    });
}
"

echo ""
echo "════════════════════════════════════════════════════════"
echo "📈 Recent Job Activity (Last 10 entries)"
echo "════════════════════════════════════════════════════════"
echo ""

tail -n 200 storage/logs/laravel.log | grep -E "🔄 REFRESH JOB STARTED|✅ REFRESH JOB COMPLETED|📤 Job Dispatched" | tail -10

echo ""
echo "════════════════════════════════════════════════════════"
echo "💡 Commands:"
echo "  - Monitor live: ./monitor-queue.sh"
echo "  - View logs: ./view-cron-logs.sh"
echo "  - Process queue: php artisan queue:work"
echo "════════════════════════════════════════════════════════"
