<?php

namespace AutoAdmin\Bundle\Content\EventListener;

use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Content\Site\SiteMatcher;
use Symfony\Component\HttpKernel\Event\RequestEvent;

class SiteRequestListener
{
    public function __construct(
        private readonly SiteContextHelper $contextHelper,
        private readonly SiteMatcher $matcher,
    )
    {
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        if ($request->attributes->get('_controller') === 'error_controller') {
            return;
        }

        if ($this->contextHelper->getSite() === null && $this->contextHelper->getLocale() === null) {
            $this->matcher->matchSite($request, $this->contextHelper);
        }
    }

    public function onKernelException(RequestEvent $event): void
    {
        $request = $event->getRequest();
        if ($request->attributes->get('_controller') === 'error_controller') {
            return;
        }

        if ($this->contextHelper->getSite() === null && $this->contextHelper->getLocale() === null) {
            $this->matcher->matchSite($request, $this->contextHelper);
        }
    }
}
