<?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\AuthBundle\Authentication;

use Serenity\CoreBundle\Notification\Command\NotificationCommand;
use Serenity\CoreBundle\Notification\Enum\PushLevel;
use Serenity\CoreBundle\Notification\Enum\PushType;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final readonly class AuthenticationAppFailureHandler implements AuthenticationFailureHandlerInterface
{
    public function __construct(private MessageBusInterface $commandBus, private RouterInterface $router, private TranslatorInterface $translator)
    {
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
    {
        $command = new NotificationCommand(
            message: $this->translator->trans('security.authentication.failure', [], 'serenity_auth_messages.admin'),
            level: PushLevel::ERROR,
            type: PushType::APP
        );
        $this->commandBus->dispatch($command);

        return new RedirectResponse($this->router->generate('app_login'));
    }
}
