<?php
declare(strict_types=1);

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

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

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

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

        return $registry;
    }

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

    public function get(string $projectionId): ?ProjectionDefinition
    {
        return $this->definitions[$projectionId] ?? 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 (ProjectionDefinition $definition): array => $definition->toArray(), $this->all());
    }
}
