<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Tests\Security;

use Ferienpass\CmsBundle\Security\JsonLoginFailureHandler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\UriSigner;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\DisabledException;

final class JsonLoginFailureHandlerTest extends TestCase
{
    public function testReturnsInvalidCredentialsForGenericException(): void
    {
        $handler = new JsonLoginFailureHandler(
            $this->createMock(UrlGeneratorInterface::class),
            $this->createMock(UriSigner::class)
        );

        $response = $handler->onAuthenticationFailure(new Request(), new AuthenticationException());
        $data = json_decode($response->getContent(), true);

        self::assertSame(401, $response->getStatusCode());
        self::assertSame('invalid_credentials', $data['error']);
    }

    public function testReturnsGenericErrorForDisabledExceptionToAvoidEnumeration(): void
    {
        $handler = new JsonLoginFailureHandler(
            $this->createMock(UrlGeneratorInterface::class),
            $this->createMock(UriSigner::class)
        );

        $response = $handler->onAuthenticationFailure(new Request(), new DisabledException());
        $data = json_decode($response->getContent(), true);

        self::assertSame(401, $response->getStatusCode());
        self::assertSame('invalid_credentials', $data['error']);
    }

    public function testUnwrapsPreviousExceptionForDisabledCase(): void
    {
        $handler = new JsonLoginFailureHandler(
            $this->createMock(UrlGeneratorInterface::class),
            $this->createMock(UriSigner::class)
        );

        $outer = new AuthenticationException('outer', 0, new DisabledException());
        $response = $handler->onAuthenticationFailure(new Request(), $outer);
        $data = json_decode($response->getContent(), true);

        self::assertSame('invalid_credentials', $data['error']);
    }
}
