<?php

namespace AutoAdmin\Bundle\Seo\EventListener;

use AutoAdmin\Bundle\Seo\Redirect\RedirectService;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\Event\RequestEvent;

class RedirectEventListener
{
    public function __construct(
        protected ManagerRegistry $doctrine,
        protected RedirectService $redirectService,
    )
    {
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $this->searchMatchingRedirect($event);
    }

    protected function searchMatchingRedirect(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        // global redirect, ignore site matching, matches across multiple domains/sites (⚠️overlapping redirects)
        $response = $this->redirectService->getRedirectResponse($event->getRequest(), true);
        if ($response) {
            $event->setResponse($response);
            return;
        }

        // classic redirect, need at least the domain
        $response = $this->redirectService->getRedirectResponse($event->getRequest());
        if ($response) {
            $event->setResponse($response);
            return; // keep this here :p
        }
    }
}
