<?php

declare(strict_types=1);

namespace Ferienpass\AdminBundle\Tests\Security;

use Ferienpass\AdminBundle\Security\AuthenticationSuccessHandler;
use Ferienpass\CoreBundle\Entity\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

final class AuthenticationSuccessHandlerTest extends TestCase
{
    public function testReturnsNullWhenUserIsNotFerienpassUser(): void
    {
        $urlGenerator = $this->createMock(UrlGeneratorInterface::class);
        $urlGenerator->expects(self::never())->method('generate');

        $token = $this->createMock(TokenInterface::class);
        $token->method('getUser')->willReturn($this->createMock(UserInterface::class));

        $handler = new AuthenticationSuccessHandler($urlGenerator);
        $result = $handler->onAuthenticationSuccess(new Request(), $token);

        self::assertNull($result);
    }

    public function testReturnsRedirectForFerienpassUser(): void
    {
        $user = new User();
        $user->setLocale('de');

        $urlGenerator = $this->createMock(UrlGeneratorInterface::class);
        $urlGenerator->expects(self::once())
            ->method('generate')
            ->with('admin_index', ['_locale' => 'de'])
            ->willReturn('/de/admin');

        $token = $this->createMock(TokenInterface::class);
        $token->method('getUser')->willReturn($user);

        $handler = new AuthenticationSuccessHandler($urlGenerator);
        $result = $handler->onAuthenticationSuccess(new Request(), $token);

        self::assertInstanceOf(RedirectResponse::class, $result);
        self::assertSame('/de/admin', $result->getTargetUrl());
    }

    public function testUserWithCustomLocaleGeneratesCorrectUrl(): void
    {
        $user = new User();
        $user->setLocale('fr');

        $urlGenerator = $this->createMock(UrlGeneratorInterface::class);
        $urlGenerator->expects(self::once())
            ->method('generate')
            ->with('admin_index', ['_locale' => 'fr'])
            ->willReturn('/fr/admin');

        $token = $this->createMock(TokenInterface::class);
        $token->method('getUser')->willReturn($user);

        $handler = new AuthenticationSuccessHandler($urlGenerator);
        $result = $handler->onAuthenticationSuccess(new Request(), $token);

        self::assertInstanceOf(RedirectResponse::class, $result);
        self::assertSame('/fr/admin', $result->getTargetUrl());
    }
}
