<?php
declare(strict_types=1);

function hv5_enqueue_job(string $type, array $payload, ?string $runAt = null): void {
    if (!hv5_table_exists('background_jobs')) return;
    db()->prepare('INSERT INTO background_jobs (job_type, payload, scheduled_at) VALUES (?,?,?)')
        ->execute([$type, json_encode($payload), $runAt ?? date('Y-m-d H:i:s')]);
}

function hv5_run_jobs(int $limit = 15): array {
    $processed = ['ota' => 0, 'jobs' => 0];
    if (function_exists('hv4_process_sync_queue')) {
        $r = hv4_process_sync_queue($limit);
        $processed['ota'] = $r['processed'] ?? 0;
    }
    if (!hv5_table_exists('background_jobs')) return $processed;
    $pdo = db();
    $rows = $pdo->query("SELECT * FROM background_jobs WHERE status='pending' AND scheduled_at <= NOW() ORDER BY id LIMIT " . (int)$limit)->fetchAll();
    foreach ($rows as $job) {
        $pdo->prepare("UPDATE background_jobs SET status='running', started_at=NOW() WHERE id=?")->execute([$job['id']]);
        try {
            $payload = json_decode($job['payload'] ?? '{}', true) ?: [];
            if ($job['job_type'] === 'ota.sync' && function_exists('hv4_process_sync_queue')) {
                hv4_process_sync_queue(5);
            }
            if ($job['job_type'] === 'ai.insights' && function_exists('hv4_generate_insights')) {
                hv4_generate_insights();
            }
            $pdo->prepare("UPDATE background_jobs SET status='done', finished_at=NOW() WHERE id=?")->execute([$job['id']]);
            $processed['jobs']++;
        } catch (Throwable $e) {
            $pdo->prepare("UPDATE background_jobs SET status='failed', last_error=?, attempts=attempts+1 WHERE id=?")
                ->execute([$e->getMessage(), $job['id']]);
        }
    }
    return $processed;
}
