<?php

declare(strict_types=1);

namespace PpPhp\Core\Manifest;

final class ManifestRegistry
{
    /** @var array<string, Manifest> */
    private array $items = [];

    public function register(Manifest $manifest): void
    {
        $this->items[$manifest->type() . ':' . $manifest->id()] = $manifest;
    }

    public function has(string $type, string $id): bool
    {
        return isset($this->items[$type . ':' . $id]);
    }

    public function get(string $type, string $id): ?Manifest
    {
        return $this->items[$type . ':' . $id] ?? null;
    }

    /** @return Manifest[] */
    public function all(): array
    {
        return array_values($this->items);
    }

    /** @return Manifest[] */
    public function byType(string $type): array
    {
        return array_values(array_filter(
            $this->items,
            static fn (Manifest $manifest): bool => $manifest->type() === $type
        ));
    }

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