<?php
declare(strict_types=1);

define('CLI_SCRIPT', true);
require __DIR__ . '/../../public/index.php';

use App\Services\MailTemplateService;
use App\Services\CronLogService;

$job = 'send_email_queue';
$start = microtime(true);

try {
    $limit = 50;
    foreach ($argv as $a) {
        if (str_starts_with($a, '--limit=')) $limit = (int) substr($a, 8);
    }
    $sent = MailTemplateService::sendPending($limit);
    $dur = (int) round((microtime(true) - $start) * 1000);
    CronLogService::record($job, 'success', "sent=$sent", $dur);
    echo "OK sent=$sent dur={$dur}ms\n";
} catch (\Throwable $e) {
    $dur = (int) round((microtime(true) - $start) * 1000);
    CronLogService::record($job, 'failed', $e->getMessage(), $dur);
    echo "FAILED: " . $e->getMessage() . "\n";
    exit(1);
}
