<?php
declare(strict_types=1);

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

final class CommandHandlerRegistry
{
    /** @var array<string, CommandHandlerDefinition> */
    private array $handlers = [];

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

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

        return $registry;
    }

    public function register(CommandHandlerDefinition $definition): CommandHandlerDefinition
    {
        $this->handlers[$definition->handlerId()] = $definition;
        return $definition;
    }

    public function findFor(CommandMessage $command): ?CommandHandlerDefinition
    {
        foreach ($this->handlers as $handler) {
            if ($handler->handles($command)) {
                return $handler;
            }
        }

        return null;
    }

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

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

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