<?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\Exception\MissingHeaderException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;

#[AsEventListener(event: LoginSuccessEvent::class, method: 'onLogin')]
final readonly class LoginSuccessListener
{
    public function __construct(
        #[Autowire(env: 'SERENITY_SAAS')]
        private bool $serenitySaas)
    {
    }

    public function onLogin(LoginSuccessEvent $event): void
    {
        $firewallName = $event->getFirewallName();
        if (!$this->serenitySaas) {
            return;
        }

        if ('app' === $firewallName) {
            if (!$event->getRequest()->headers->has('x-serenity-id')) {
                throw new MissingHeaderException('x-serenity-id');
            }
            $event->getRequest()->getSession()->set('project_identifier', $event->getRequest()->headers->get('x-serenity-id'));
        }
    }
}
