<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming;

final class MessageBusTopicRegistry
{
    /** @var array<string, MessageBusTopic> */
    private array $topics = [];

    public static function fromArray(array $items): self
    {
        $registry = new self();

        foreach ($items as $item) {
            if (is_array($item)) {
                $registry->put(MessageBusTopic::fromArray($item));
            }
        }

        return $registry;
    }

    public function register(string $topic, int $priority = 0): MessageBusTopic
    {
        if (!isset($this->topics[$topic])) {
            $this->topics[$topic] = MessageBusTopic::register($topic, $priority);
        }

        return $this->topics[$topic];
    }

    public function put(MessageBusTopic $topic): void
    {
        $this->topics[$topic->name()] = $topic;
    }

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

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

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

    public function toArray(): array
    {
        return array_map(static fn (MessageBusTopic $topic): array => $topic->toArray(), $this->all());
    }
}
