<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Routing;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

final readonly class ChillUrlGenerator implements ChillUrlGeneratorInterface
{
    public function __construct(private UrlGeneratorInterface $urlGenerator, private RequestStack $requestStack) {}

    public function generate(string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        return $this->urlGenerator->generate($name, $parameters, $referenceType);
    }

    public function generateWithReturnPath(string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        $uri = $this->requestStack->getCurrentRequest()->getRequestUri();

        return $this->urlGenerator->generate($name, [...$parameters, 'returnPath' => $uri], $referenceType);
    }

    public function returnPathOr(string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        $request = $this->requestStack->getCurrentRequest();

        if ($request->query->has('returnPath')) {
            return $request->query->get('returnPath');
        }

        return $this->urlGenerator->generate($name, $parameters, $referenceType);
    }

    public function forwardReturnPath(string $name, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        $request = $this->requestStack->getCurrentRequest();

        if ($request->query->has('returnPath')) {
            return $this->urlGenerator->generate($name, [...$parameters, 'returnPath' => $request->query->get('returnPath')], $referenceType);
        }

        return $this->urlGenerator->generate($name, $parameters, $referenceType);
    }
}
