<?php
require_once __DIR__ . "/app/db.php";

function run_queue(): void {
  $pdo = smm_db();
  $now = smm_now_iso();
  $st = $pdo->prepare("SELECT * FROM cron_queue WHERE status='queued' AND run_at <= ? ORDER BY run_at ASC LIMIT 5");
  $st->execute([$now]);
  $jobs = $st->fetchAll(PDO::FETCH_ASSOC);

  foreach ($jobs as $job) {
    $id = intval($job['id']);
    $jobType = $job['job_type'];
    $payload = json_decode($job['payload_json'] ?? '{}', true);
    if (!is_array($payload)) $payload = [];
    $pdo->prepare("UPDATE cron_queue SET status='running', updated_at=? WHERE id=?")->execute([$now,$id]);

    try {
      // For Phase 9.1: just mark as done (adapters come in Phase 10)
      $pdo->prepare("UPDATE cron_queue SET status='done', updated_at=? WHERE id=?")->execute([smm_now_iso(),$id]);
      echo "[OK] job#$id $jobType\n";
    } catch (Throwable $e) {
      $pdo->prepare("UPDATE cron_queue SET status='error', attempts=attempts+1, last_error=?, updated_at=? WHERE id=?")
          ->execute([$e->getMessage(), smm_now_iso(), $id]);
      echo "[ERR] job#$id $jobType ".$e->getMessage()."\n";
    }
  }
}

run_queue();
