<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Console;

use PpPhp\Core\Platform\Console\Contracts\CommandInterface;

final class CommandRegistry
{
    /** @var array<string, CommandInterface> */
    private array $commands = [];

    public function register(CommandInterface $command): void
    {
        $this->commands[$command->name()] = $command;
    }

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

    public function get(string $name): ?CommandInterface
    {
        return $this->commands[$name] ?? null;
    }

    /** @return CommandInterface[] */
    public function all(): array
    {
        ksort($this->commands);

        return array_values($this->commands);
    }

    public function names(): array
    {
        $names = array_keys($this->commands);
        sort($names);

        return $names;
    }

    public function toArray(): array
    {
        return array_map(static fn (CommandInterface $command): array => [
            'name' => $command->name(),
            'description' => $command->description(),
        ], $this->all());
    }
}
