<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
    public function onLogoutSuccess(Request $request, TokenInterface $token): Response
    {
        // Essayer de récupérer l'URL referer
        $referer = $request->headers->get('referer');

        // Vérifier que le referer n'est pas une URL de logout ou login
        if ($referer && !str_contains($referer, '/logout') && !str_contains($referer, '/login')) {
            return new RedirectResponse($referer);
        }

        // Sinon rediriger vers la page d'accueil
        return new RedirectResponse('/');
    }
}

