<?php

namespace App\Modules\Shared\Infraestructure\Query;

use App\Modules\Shared\Domain\Bus\Query\Query;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use App\Modules\Shared\Domain\Bus\Query\Response;


final class InMemoryQueryBus implements QueryBus
{

    private $queries = [];

    public function __construct() {}

    public function ask(Query $query): ?Response
    {
        $className = get_class($query);
        $classHandler = $className . 'Handler';
        if (!class_exists($classHandler)) {
            throw new BadRequestException('Handler doesn\'t exists');
        }
        return (app()->make($classHandler))($query);
    }

    public function register(array $map): void
    {
        foreach ($map as $command => $handler) {
            $this->queries[$command] = $handler;
        }
    }
}
