<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Console;

final class CommandBus
{
    public function __construct(
        private readonly CommandRegistry $registry
    ) {}

    public function registry(): CommandRegistry
    {
        return $this->registry;
    }

    public function dispatch(string $name, array $arguments = []): int
    {
        $command = $this->registry->get($name);

        if (!$command) {
            echo "Unknown command: {$name}" . PHP_EOL . PHP_EOL;
            $this->help();
            return 1;
        }

        return $command->handle($arguments);
    }

    public function help(): int
    {
        echo "PPphp Platform" . PHP_EOL;
        echo "==============" . PHP_EOL . PHP_EOL;
        echo "Available commands:" . PHP_EOL;

        foreach ($this->registry->all() as $command) {
            echo "  " . str_pad($command->name(), 22) . $command->description() . PHP_EOL;
        }

        echo PHP_EOL;
        return 0;
    }
}
