<?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\CoreBundle\Tests\Security;

use Ferienpass\CoreBundle\Repository\ApiTokenRepository;
use Ferienpass\CoreBundle\Security\ApiTokenHandler;
use Ferienpass\CoreBundle\Security\Exception\BlockedEmailException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

final class ApiTokenHandlerTest extends TestCase
{
    // ---- BlockedEmailException ----

    public function testBlockedEmailExceptionMessageKey(): void
    {
        $e = new BlockedEmailException();
        self::assertNotEmpty($e->getMessageKey());
    }

    // ---- ApiTokenHandler ----

    public function testGetUserBadgeFromThrowsWhenPrefixMissing(): void
    {
        $this->expectException(BadCredentialsException::class);

        $repo = $this->createMock(ApiTokenRepository::class);
        $hasher = $this->createMock(PasswordHasherFactoryInterface::class);

        new ApiTokenHandler($repo, $hasher)->getUserBadgeFrom('invalid-token.secret');
    }

    public function testGetUserBadgeFromThrowsWhenNoDotSeparator(): void
    {
        $this->expectException(BadCredentialsException::class);

        $repo = $this->createMock(ApiTokenRepository::class);
        $hasher = $this->createMock(PasswordHasherFactoryInterface::class);

        // Has prefix but no dot
        new ApiTokenHandler($repo, $hasher)->getUserBadgeFrom('pat-noseparator');
    }

    public function testGetUserBadgeFromThrowsWhenTokenNotFoundInRepository(): void
    {
        $this->expectException(BadCredentialsException::class);

        $repo = $this->createMock(ApiTokenRepository::class);
        $repo->method('findOneBy')->willReturn(null);

        $hasher = $this->createMock(PasswordHasherFactoryInterface::class);

        new ApiTokenHandler($repo, $hasher)->getUserBadgeFrom('pat-locator.secret');
    }
}
