<?php
declare(strict_types=1);

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

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

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

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

        return $registry;
    }

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

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

    public function startersFor(string $eventType): array
    {
        return array_values(array_filter(
            $this->definitions,
            static fn (SagaDefinition $definition): bool => $definition->startsWith($eventType)
        ));
    }

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

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