<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Twig\Environment;

class TwigGlobalSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly Environment         $twig,
        private readonly AuthenticationUtils $authUtils,
    ) {}

    public function onKernelController(ControllerEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        try {
            $this->twig->addGlobal('error',         $this->authUtils->getLastAuthenticationError());
            $this->twig->addGlobal('last_username', $this->authUtils->getLastUsername());
        } catch (\LogicException) {
            // Route hors pare-feu (assets, profiler...) — on ignore
            $this->twig->addGlobal('error',         null);
            $this->twig->addGlobal('last_username', '');
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::CONTROLLER => 'onKernelController',
        ];
    }
}
