<?php

declare(strict_types=1);

namespace PpPhp\Core\Maintenance\Registry;

use PpPhp\Core\Maintenance\Contracts\MaintenanceProviderInterface;

final class MaintenanceProviderRegistry
{
    /**
     * @var array<string, MaintenanceProviderInterface>
     */
    private array $providers = [];

    public function register(MaintenanceProviderInterface $provider): void
    {
        $this->providers[$provider->id()] = $provider;

        uasort(
            $this->providers,
            static fn (MaintenanceProviderInterface $a, MaintenanceProviderInterface $b): int => $a->priority() <=> $b->priority()
        );
    }

    public function has(string $id): bool
    {
        return isset($this->providers[$id]);
    }

    public function get(string $id): ?MaintenanceProviderInterface
    {
        return $this->providers[$id] ?? null;
    }

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