<?php


namespace AutoAdmin\Bundle\Admin\Controller\Admin;


use AutoAdmin\Bundle\Core\Util\CaseConverter;
use Exception;
use ReflectionClass;
use ReflectionException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ForwardController extends AbstractAdminController
{
    /**
     * @throws ReflectionException
     */
    public function index(Request $request, CaseConverter $caseConverter): Response
    {
        $controllerSlug = $request->get('controller');
        $controller = $this->configManager->getControllerConfigBySlug($controllerSlug);
        $controllerClass = $controller['class'];
        $method = $request->get('method');
        $method = $caseConverter->kebabToCamelCase($method);

        $refl = new ReflectionClass($controllerClass);
        if (!$refl->hasMethod($method)) {
            throw new Exception(
                sprintf(
                    'Impossible to forward request: method "%s" does not exist inside "%s" controller.',
                    $method,
                    $controllerClass
                )
            );
        }

        $controllerString = $controllerClass . '::' . $method;

        // keep query and parameters
        $query = $request->query->all();
        $path = $request->attributes->all();
        unset($path['_controller']);

        return $this->forward($controllerString, $path, $query);
    }
}
