<?php
require_once __DIR__ . '/../app/Core.php';
require_once __DIR__ . '/../app/services.php';
require_once __DIR__ . '/../app/models/QueueJob.php';
require_once __DIR__ . '/../app/models/Setting.php';

date_default_timezone_set(config('app.timezone', 'America/Chicago'));
$queue = new QueueJob();
$service = new CampaignService();
$settings = new Setting();
$settings->set('worker_last_heartbeat', date('Y-m-d H:i:s'));
$processed = 0;
$limit = (int)config('queue.worker_batch_limit', 50);
$maxAttempts = (int)config('queue.max_attempts', 4);
$baseDelay = (int)config('queue.retry_delay_minutes', 5);

while ($processed < $limit && ($job = $queue->nextRunnable('campaign_process'))) {
    $settings->set('worker_last_heartbeat', date('Y-m-d H:i:s'));
    $queue->markProcessing((int)$job['id']);
    try {
        $payload = json_decode((string)$job['payload_json'], true) ?: [];
        $service->processCampaign((int)($payload['campaign_id'] ?? 0));
        $queue->markDone((int)$job['id']);
        $processed++;
    } catch (Throwable $e) {
        $attempts = (int)$job['attempts'] + 1;
        if ($attempts < $maxAttempts) {
            $delay = $baseDelay * max(1, $attempts);
            $queue->releaseForRetry((int)$job['id'], $e->getMessage(), $delay);
        } else {
            $queue->markFailed((int)$job['id'], $e->getMessage());
        }
    }
}

$settings->set('worker_last_heartbeat', date('Y-m-d H:i:s'));
echo 'Processed queue jobs: ' . $processed . PHP_EOL;
