<?php
declare(strict_types = 1);
namespace Opentalent\OtOptimizer\XClass\Frontend\Middleware;

use Opentalent\OtOptimizer\Routing\SiteMatcher;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 */
class SiteResolver extends \TYPO3\CMS\Frontend\Middleware\SiteResolver
{
    private bool $shallFallback;

    public function __construct($matcher = null)
    {
        $this->shallFallback = $_COOKIE['optimize'] != 1;

        if ($this->shallFallback) {
            parent::__construct($matcher);
        }
    }

    /**
     * Resolve the site/language information by checking the page ID or the URL.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->shallFallback) {
            return parent::process($request, $handler);
        }

        $matcher = GeneralUtility::makeInstance(ObjectManager::class)->get(SiteMatcher::class);
        $routeResult = $matcher->matchRequest($request);

        $request = $request->withAttribute('site', $routeResult->getSite());
        $request = $request->withAttribute('language', $routeResult->getLanguage());
        $request = $request->withAttribute('routing', $routeResult);

        // At this point, we later get further route modifiers
        // for bw-compat we update $GLOBALS[TYPO3_REQUEST] to be used later in TSFE.
        $GLOBALS['TYPO3_REQUEST'] = $request;

        return $handler->handle($request);
    }
}
