<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Tests\Commerce\Catalog\Api\Security;

use CpCreation\VitiCore\Commerce\Catalog\Api\Security\CommerceAccessTokenHandler;
use CpCreation\VitiCore\Commerce\Catalog\Api\Security\CatalogHubJwtVerifier;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogHubConfiguration;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogIntegrationConfiguration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;

final class CommerceAccessTokenHandlerTest extends TestCase
{
    private const INSTANCE_ID = 'e1f7fbf7-b430-44cc-91a6-29e0503be011';
    private const TOKEN = 'a-long-random-commerce-token';

    public function testItBuildsAnIsolatedMachineUserForAValidToken(): void
    {
        $handler = $this->handler($this->configuration());

        $badge = $handler->getUserBadgeFrom(self::TOKEN);
        $user = $badge->getUser();

        self::assertSame('commerce-sync:' . self::INSTANCE_ID, $badge->getUserIdentifier());
        self::assertInstanceOf(PasswordAuthenticatedUserInterface::class, $user);
        self::assertSame(['ROLE_COMMERCE_SYNC'], $user->getRoles());
        self::assertNull($user->getPassword());
    }

    public function testItRejectsAnInvalidToken(): void
    {
        $handler = $this->handler($this->configuration());

        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('Invalid credentials.');

        $handler->getUserBadgeFrom('another-token');
    }

    public function testItRejectsEveryTokenWhenTheIntegrationIsDisabled(): void
    {
        $handler = $this->handler($this->configuration(false));

        $this->expectException(BadCredentialsException::class);

        $handler->getUserBadgeFrom(self::TOKEN);
    }

    private function configuration(bool $enabled = true): CatalogIntegrationConfiguration
    {
        return new CatalogIntegrationConfiguration(
            $enabled,
            self::INSTANCE_ID,
            hash('sha256', self::TOKEN),
            'EUR',
        );
    }

    private function handler(CatalogIntegrationConfiguration $configuration): CommerceAccessTokenHandler
    {
        $hubConfiguration = new CatalogHubConfiguration('', '', '', '', '', '', false);

        return new CommerceAccessTokenHandler(
            $configuration,
            new CatalogHubJwtVerifier($hubConfiguration, $configuration),
        );
    }
}
