<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Services\Registry;

use PpPhp\Core\Platform\Services\Metadata\CapabilityMetadata;

final class CapabilityRegistry
{
    /** @var array<string, CapabilityMetadata[]> */
    private array $capabilities = [];

    public function register(string $serviceId, CapabilityMetadata $capability): void
    {
        $this->capabilities[$serviceId][$capability->id()] = $capability;
    }

    /**
     * @return CapabilityMetadata[]
     */
    public function forService(string $serviceId): array
    {
        return array_values($this->capabilities[$serviceId] ?? []);
    }

    public function has(string $serviceId, string $capabilityId): bool
    {
        return isset($this->capabilities[$serviceId][$capabilityId]);
    }

    public function all(): array
    {
        $out = [];

        foreach ($this->capabilities as $serviceId => $items) {
            $out[$serviceId] = array_map(
                static fn (CapabilityMetadata $capability): array => $capability->toArray(),
                array_values($items)
            );
        }

        return $out;
    }
}
