<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Routing;

use Contao\CoreBundle\Routing\ContentUrlGenerator;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;

class LocaleContentUrlGeneratorDecorator extends ContentUrlGenerator
{
    public function __construct(
        private readonly ContentUrlGenerator $inner,
        private readonly RequestStack $requestStack,
    ) {
    }

    public function generate(object $content, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        $request = $this->requestStack->getCurrentRequest();
        $locale = $parameters['_locale'] ?? $request?->attributes->get('_locale');
        unset($parameters['_locale']);

        $url = $this->inner->generate($content, $parameters, $referenceType);

        if ($locale) {
            $prefix = LocaleRouteProviderDecorator::MAP[$locale] ?? '';

            if ('' !== $prefix) {
                if (str_starts_with($url, '/') && !str_starts_with($url, '//')) {
                    if ($url === '/'.$prefix || str_starts_with($url, '/'.$prefix.'/')) {
                        return $url;
                    }

                    return '/'.$prefix.$url;
                }
            }
        }

        return $url;
    }

    public function setContext(RequestContext $context): void
    {
        $this->inner->setContext($context);
    }

    public function getContext(): RequestContext
    {
        return $this->inner->getContext();
    }

    public function reset(): void
    {
        $this->inner->reset();
    }
}
