<?php

declare(strict_types=1);

namespace PpPhp\Core\Discovery;

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

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

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

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

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

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

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