<?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 Serenity\SaasBundle\EventListener;

use Serenity\CoreBundle\Saas\SerenitySaasContext;
use Serenity\SaasBundle\Exception\MissingHeaderException;
use Serenity\SaasBundle\Resolver\ProjectResolver;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

#[AsEventListener(event: KernelEvents::REQUEST, priority: 100)]
readonly class SerenitySaasContextListener
{
    public function __construct(
        #[Autowire(env: 'SERENITY_SAAS')]
        private bool $serenitySaas,
        #[Autowire(env: 'ADMIN_HOST')]
        private string $adminHost,
        private ProjectResolver $projectResolver,
    ) {
    }

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

        if (!$event->isMainRequest()) {
            return;
        }

        if (
            !$this->serenitySaas
            || str_starts_with($request->getPathInfo(), '/_wdt')
            || str_starts_with($request->getPathInfo(), '/_profiler')
            || str_starts_with($request->getPathInfo(), '/media')
        ) {
            return;
        }

        if ('_exit' === $request->query->get('_switch')) {
            $request->getSession()->remove('project_identifier');
            SerenitySaasContext::$identifierSerenityId = null;

            return;
        }

        if ($request->getSession()->has('project_identifier')) {
            SerenitySaasContext::$identifierSerenityId = $request->getSession()->get('project_identifier');

            return;
        }

        $project = $this->projectResolver->getProject();

        if (!$project && $request->getHost() !== $this->adminHost && !str_starts_with($request->getPathInfo(), '/dashboard')) {
            throw new MissingHeaderException('Unknown host: '.$request->getHost());
        }

        SerenitySaasContext::$identifierSerenityId = $project?->getIdentifier(); // ou getId()
    }
}
