<?php
declare(strict_types=1);

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

final class EventUpcasterRegistry
{
    private array $upcasters = [];

    public static function fromArray(array $items): self
    {
        $registry = new self();
        foreach ($items as $item) {
            if (is_array($item)) { $registry->register(EventUpcaster::fromArray($item)); }
        }
        return $registry;
    }

    public function register(EventUpcaster $upcaster): EventUpcaster
    {
        $this->upcasters[$upcaster->upcasterId()] = $upcaster;
        return $upcaster;
    }

    public function find(string $eventType, int $fromVersion): ?EventUpcaster
    {
        foreach ($this->upcasters as $upcaster) {
            if ($upcaster->eventType() === $eventType && $upcaster->fromVersion() === $fromVersion && $upcaster->active()) { return $upcaster; }
        }
        return null;
    }

    public function all(): array { return array_values($this->upcasters); }
    public function count(): int { return count($this->upcasters); }
    public function toArray(): array { return array_map(static fn (EventUpcaster $upcaster): array => $upcaster->toArray(), $this->all()); }
}
