<?php
declare(strict_types=1);

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

final class EventVersionRegistry
{
    private array $versions = [];

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

    public function register(EventVersion $version): EventVersion
    {
        $this->versions[$version->eventType()] = $version;
        return $version;
    }

    public function currentVersion(string $eventType): int
    {
        return isset($this->versions[$eventType]) ? $this->versions[$eventType]->version() : 1;
    }

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