<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;

final readonly class VerifyListener implements EventSubscriberInterface
{
    public function __construct(
        private RouterInterface $router,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => [['onKernelRequest', 10]],
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();

        $userAgent = (string) $request->headers->get('User-Agent', '');
        if (preg_match('/baidu|dareboost|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|slurp|teoma|twitter|yandex|yeti|speed|insights|woobot|ighth|tmetr|eadle|gtmetrix|lighthouse/i', $userAgent)) {
            return;
        }

        if (!$event->isMainRequest() || preg_match('/media\/cache\/resolve/', $request->getRequestUri())) {
            return;
        }

        $session = $request->getSession();
        $route = (string) $request->attributes->get('_route');
        $locale = $request->getLocale();
        $controller = (string) $request->attributes->get('_controller', '');

        if (!$session->get('verify') && !$session->get('route')) {
            $session->set('route', $route);
        }

        if ($session->get('route') && Request::METHOD_POST === $request->getMethod() && !$session->get('verify')) {
            $session->set('verify', true);
        }

        if ($session->get('route') && true === $session->get('verify') && Request::METHOD_POST === $request->getMethod()) {
            if ('homepage' === $route && !$request->request->get('contact')) {
                $url = $this->router->generate($route, ['_locale' => $locale]);
                $event->setResponse(new RedirectResponse($url));

                return;
            }

            return;
        }

        $pathInfo = $request->getPathInfo();
        $requestUri = $request->getRequestUri();

        $isExcluded =
            'verify' === $route
            || 'redirect-cuvee' === $route
            || preg_match('/Controller\\\\Admin/', $controller)
            || preg_match('/Controller\\\\Site\\\\MethodPaymentController/', $controller)
            || (1 === mb_strpos($pathInfo, 'request'))
            || (1 === mb_strpos($pathInfo, '.well-known'))
            || (1 === mb_strpos($pathInfo, '_wdt'))
            || (1 === mb_strpos($pathInfo, '_profiler'))
            || preg_match('/utm_campaign/', $requestUri);

        if (!$isExcluded && !$session->get('verify')) {
            $event->setResponse(new RedirectResponse($this->router->generate('verify')));
        }
    }
}
