<?php

namespace App\EventListener;

use App\Entity\User;
use App\Service\AppLoggerService;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

#[AsEventListener(event: KernelEvents::CONTROLLER, priority: -10)]
class AdminLogListener
{
    public function __construct(
        private AppLoggerService $logger,
        private TokenStorageInterface $tokenStorage,
    ) {
    }

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

        $request = $event->getRequest();
        $route = $request->attributes->get('_route', '');

        if (!str_starts_with($route, 'app_admin_')) {
            return;
        }

        // Ignorer les requetes AJAX de recherche pour eviter le spam de logs
        if ($request->isXmlHttpRequest() && str_contains($route, 'search')) {
            return;
        }

        $user = null;
        $token = $this->tokenStorage->getToken();
        if (null !== $token && $token->getUser() instanceof User) {
            $user = $token->getUser();
        }

        try {
            $this->logger->log(
                $request->getMethod(),
                $request->getRequestUri(),
                $route,
                $user,
                $request->getClientIp(),
            );
        } catch (\Throwable) {
            // Ne jamais bloquer la requete si le logging echoue
        }
    }
}
