<?php

/**
 * Worker para processar retries de webhooks
 * Executar via cron: */5 * * * * php scripts/webhook-retry-worker.php
 */

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

use Gestoreasy\Core\Tenant\ConnectionManager;
use Modules\APIPublica\Services\WebhookService;

// Buscar todos os tenants ativos
$adminPdo = \Gestoreasy\Core\Admin\ConnectionManager::getConnection();
$tenants = $adminPdo->query('SELECT id FROM tenants WHERE active = 1')->fetchAll(PDO::FETCH_COLUMN);

foreach ($tenants as $tenantId) {
    try {
        // Definir contexto do tenant
        \Gestoreasy\Core\Tenant\TenantContext::setTenantId($tenantId);
        
        // Processar retries
        $webhookService = new WebhookService($tenantId);
        $webhookService->processarRetries();
        
        echo "Processados retries para tenant: {$tenantId}\n";
    } catch (Exception $e) {
        echo "Erro ao processar tenant {$tenantId}: " . $e->getMessage() . "\n";
    }
}

echo "Processamento de retries concluído.\n";

