<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Worker;

use PpPhp\Core\Platform\Event\Worker\Contracts\WorkerInterface;

final class WorkerRegistry
{
    private array $workers = [];

    public function register(WorkerInterface $worker): void
    {
        $this->workers[$worker->id()] = $worker;
    }

    public function get(string $id): ?WorkerInterface
    {
        return $this->workers[$id] ?? null;
    }

    public function all(): array
    {
        return array_values($this->workers);
    }

    public function count(): int
    {
        return count($this->workers);
    }

    public function toArray(): array
    {
        return array_map(static fn (WorkerInterface $worker): array => [
            'id' => $worker->id(),
            'name' => $worker->name(),
            'status' => $worker->status()->toArray(),
            'heartbeat' => $worker->heartbeat(),
        ], $this->all());
    }
}
