<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;

class ProcessAdsQueue extends Command
{
    protected $signature = 'ads:process-queue {--timeout=300 : Timeout in seconds}';
    protected $description = 'Process ads-related queue jobs';

    public function handle()
    {
        $timeout = (int) $this->option('timeout');
        $this->info("🔄 Processing ads queue for {$timeout} seconds...");

        $startTime = time();
        $processedJobs = 0;

        while ((time() - $startTime) < $timeout) {
            // Check for pending jobs
            $pendingJobs = DB::table('jobs')->count();

            if ($pendingJobs === 0) {
                $this->info('✅ No pending jobs found');
                break;
            }

            $this->info("📋 Found {$pendingJobs} pending jobs");

            // Process one job
            try {
                Artisan::call('queue:work', [
                    '--once' => true,
                    '--timeout' => 60
                ]);

                $processedJobs++;
                $this->info("✅ Processed job #{$processedJobs}");

            } catch (\Throwable $e) {
                $this->error("❌ Error processing job: " . $e->getMessage());
            }

            // Small delay to prevent overwhelming
            sleep(1);
        }

        $this->info("🏁 Queue processing completed. Processed {$processedJobs} jobs in " . (time() - $startTime) . " seconds");
        return 0;
    }
}
