<?php

declare(strict_types=1);

namespace PpPhp\Core\Diagnostics\Metadata;

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

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

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

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

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

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

    public function countByType(string $type): int
    {
        return count($this->byType($type));
    }

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