<?php

namespace App\Framework\CommandBus;

use App\Framework\Context\ExecutionContext;
use App\Framework\DI\DefaultContainer;
use App\Framework\DI\Initializer;
use App\Framework\Discovery\Results\DiscoveryResults;

final readonly class CommandBusInitializer
{
    public function __construct(
        private DefaultContainer $container,
        private DiscoveryResults $results,
        private ExecutionContext $executionContext,
    ) {}

    #[Initializer]
    public function __invoke(): CommandBus
    {
        $this->results->get(CommandHandler::class);

        $handlers = [];
        foreach($this->results->get(CommandHandler::class) as $handler) {

            $handlers[] = CommandHandlerDescriptor::fromHandlerArray($handler);
        }
        $handlersCollection = new CommandHandlersCollection(...$handlers);

        return new DefaultCommandBus($handlersCollection, $this->container, $this->executionContext);
    }
}
