<?php
namespace App; use App\DB; use PDO;


final class Queue
{
public static function push(string $type, array $payload, int $delaySec=0): void
{
DB::pdo()->prepare('INSERT INTO jobs(type, payload, available_at) VALUES(?,?, DATE_ADD(NOW(), INTERVAL ? SECOND))')
->execute([$type, json_encode($payload, JSON_UNESCAPED_UNICODE), $delaySec]);
}


public static function reserveNext(int $timeoutMs=250): ?array
{
$pdo = DB::pdo();
return DB::tx(function(PDO $pdo){
$row = $pdo->query("SELECT * FROM jobs WHERE status='PENDING' AND available_at<=NOW() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED")->fetch();
if (!$row) return null;
$pdo->prepare("UPDATE jobs SET status='RUNNING', reserved_at=NOW() WHERE id=?")->execute([$row['id']]);
return $row;
});
}


public static function done(int $id): void
{ DB::pdo()->prepare("UPDATE jobs SET status='DONE', done_at=NOW() WHERE id=?")->execute([$id]); }


public static function fail(int $id): void
{ DB::pdo()->prepare("UPDATE jobs SET status='FAILED' WHERE id=?")->execute([$id]); }
}