<?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\SaasBundle\Doctrine\Repository\ProjectRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

#[AsEventListener(event: KernelEvents::RESPONSE)]
final readonly class AdminCheckSaasIdentifierBeforeResponseListener
{
    public function __construct(private AuthorizationCheckerInterface $authChecker,
        private RouterInterface $router,
        private RequestStack $requestStack,
        private ProjectRepository $projectRepository,
        #[Autowire('%serenity_saas%')]
        private bool $serenitySaas)
    {
    }

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

        if (!$this->serenitySaas || !$event->isMainRequest()) {
            return;
        }
        if ($this->authChecker->isGranted('ROLE_ADMIN') && $event->getRequest()->query->has('project_identifier')) {
            $this->requestStack->getSession()->remove('project_identifier');

            return;
        }

        if (!$this->authChecker->isGranted('ROLE_TENANT') || !str_starts_with($event->getRequest()->getPathInfo(), '/dashboard') || str_starts_with($request->attributes->get('_route'), 'admin_saas_select_project')) {
            return;
        }

        if ($this->requestStack->getSession()->has('project_identifier')) {
            $project = $this->projectRepository->getProjectsByIdentifier($this->requestStack->getSession()->get('project_identifier'));
            if (!$project || $project->isDisabled()) {
                $this->requestStack->getSession()->remove('project_identifier');
                $response = new RedirectResponse($this->router->generate('admin_saas_select_project'));
                $event->setResponse($response);
            }
        }
    }
}
