<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Psr\Log\LoggerInterface;

class LoginFailureHandler implements AuthenticationFailureHandlerInterface
{
    public function __construct(
        private readonly HttpUtils $httpUtils,
        private readonly ?LoggerInterface $logger = null,
    ) {
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
    {
        // Récupérer la session et ajouter un message flash
        $session = $request->getSession();
        $session->getFlashBag()->add('error', 'Alors, Tu as PERDU (tes identifiants) ?');

        // Rediriger vers la page de référence ou vers la racine
        $targetUrl = $request->headers->get('referer') ?? $this->httpUtils->generateUrl($request, 'app_login');

        return $this->httpUtils->createRedirectResponse($request, $targetUrl);
    }
}



