<?php
/**
 * Worker para processar filas de jobs
 * 
 * Uso: php scripts/queue-worker.php <queue_name> [--timeout=5] [--max-jobs=100]
 */

require_once __DIR__ . '/../vendor/autoload.php';

use Gestoreasy\Core\Queue\QueueService;
use Gestoreasy\Core\Queue\JobInterface;

// Configurar ambiente
$envFile = __DIR__ . '/../.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
    }
}

// Argumentos
$queueName = $argv[1] ?? 'default';
$timeout = 5;
$maxJobs = 100;

foreach ($argv as $arg) {
    if (strpos($arg, '--timeout=') === 0) {
        $timeout = (int)substr($arg, 10);
    }
    if (strpos($arg, '--max-jobs=') === 0) {
        $maxJobs = (int)substr($arg, 11);
    }
}

echo "Starting queue worker for queue: {$queueName}\n";
echo "Timeout: {$timeout}s, Max jobs: {$maxJobs}\n\n";

$queueService = new QueueService();

if (!$queueService->isEnabled()) {
    echo "ERROR: Queue service is not enabled. Check Redis configuration.\n";
    exit(1);
}

$processed = 0;
$failed = 0;

while ($processed < $maxJobs) {
    $job = $queueService->pop($queueName, $timeout);

    if ($job === null) {
        // Nenhum job disponível, aguardar um pouco
        sleep(1);
        continue;
    }

    $jobId = $job['id'];
    $jobClass = $job['class'];
    $jobData = $job['data'] ?? [];

    echo "[{$processed}] Processing job: {$jobId} ({$jobClass})\n";

    try {
        // Verificar se a classe existe
        if (!class_exists($jobClass)) {
            throw new Exception("Job class not found: {$jobClass}");
        }

        // Verificar se implementa JobInterface
        if (!is_subclass_of($jobClass, JobInterface::class)) {
            throw new Exception("Job class does not implement JobInterface: {$jobClass}");
        }

        // Instanciar e executar job
        $jobInstance = new $jobClass();
        $jobInstance->handle($jobData);

        // Marcar como processado
        $queueService->markAsProcessed($queueName, $jobId);
        echo "  ✓ Job processed successfully\n";
        $processed++;

    } catch (Exception $e) {
        echo "  ✗ Job failed: " . $e->getMessage() . "\n";
        $queueService->markAsFailed($queueName, $jobId, $e->getMessage());
        $failed++;
    }
}

echo "\nWorker finished. Processed: {$processed}, Failed: {$failed}\n";

