<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Query;

final class ReadModelRegistry
{
    /** @var array<string, ReadModelDefinition> */
    private array $definitions = [];

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

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

        return $registry;
    }

    public function register(ReadModelDefinition $definition): ReadModelDefinition
    {
        $this->definitions[$definition->readModelId()] = $definition;
        return $definition;
    }

    public function get(string $readModelId): ?ReadModelDefinition
    {
        return $this->definitions[$readModelId] ?? null;
    }

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

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

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