<?php

declare(strict_types=1);

namespace App\Infrastructure\Jobs;

use App\Domain\Jobs\Job;
use RuntimeException;

/**
 * Holds the canonical list of registered jobs. The container fills this on
 * boot; the JobsController and TickJob look up jobs by name.
 *
 * Order of registration matters only for the tick dispatcher's iteration —
 * not for correctness, but `tick` will execute due jobs in registration
 * order.
 */
final class JobRegistry
{
    /** @var array<string, Job> */
    private array $jobs = [];

    public function register(Job $job): void
    {
        $this->jobs[$job->name()] = $job;
    }

    public function get(string $name): Job
    {
        if (!isset($this->jobs[$name])) {
            throw new RuntimeException(sprintf('Unknown job: %s', $name));
        }

        return $this->jobs[$name];
    }

    public function has(string $name): bool
    {
        return isset($this->jobs[$name]);
    }

    /**
     * @return array<string, Job>
     */
    public function all(): array
    {
        return $this->jobs;
    }
}
