<?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\Configuration;

use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogSecretCipher;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\DoctrineCatalogConfigurationProvider;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogConfiguration;
use CpCreation\VitiCore\Commerce\Catalog\Repository\CatalogConfigurationStore;
use PHPUnit\Framework\TestCase;
use Ramsey\Uuid\Uuid;

final class DoctrineCatalogConfigurationProviderTest extends TestCase
{
    private const string INSTANCE_ID = '7ad9e145-910f-4de4-9cec-5f832494adef';

    public function testItBuildsTheRuntimeSnapshotFromEncryptedPersistentConfiguration(): void
    {
        $cipher = new CatalogSecretCipher('a-strong-test-application-secret');
        $configuration = $this->configuredEntity($cipher);
        $store = $this->createStub(CatalogConfigurationStore::class);
        $store->method('get')->willReturn($configuration);

        $snapshot = new DoctrineCatalogConfigurationProvider($store, $cipher, false)->current();

        self::assertNotNull($snapshot);
        self::assertTrue($snapshot->enabled);
        self::assertSame(self::INSTANCE_ID, $snapshot->instanceId);
        self::assertSame('https://hub.example', $snapshot->hubUrl);
        self::assertSame('long-lived-enrollment-token', $snapshot->enrollmentToken);
        self::assertNotNull($snapshot->webhookSecret);
        self::assertGreaterThanOrEqual(32, mb_strlen($snapshot->webhookSecret));
        self::assertSame('serenity-commerce-hub', $snapshot->jwtIssuer);
        self::assertSame('hub-main', $snapshot->jwtKeyId);
    }

    public function testResetForcesALongRunningWorkerToReloadConfiguration(): void
    {
        $cipher = new CatalogSecretCipher('a-strong-test-application-secret');
        $first = $this->configuredEntity($cipher);
        $second = new CatalogConfiguration(Uuid::fromString(self::INSTANCE_ID));
        $second->setHubUrl('https://new-hub.example');
        $second->prepareActivation($cipher);
        $store = $this->createMock(CatalogConfigurationStore::class);
        $store->expects(self::exactly(2))
            ->method('get')
            ->willReturnOnConsecutiveCalls($first, $second);
        $provider = new DoctrineCatalogConfigurationProvider($store, $cipher, false);

        self::assertSame('https://hub.example', $provider->current()?->hubUrl);
        self::assertSame('https://hub.example', $provider->current()?->hubUrl);

        $provider->reset();

        self::assertSame('https://new-hub.example', $provider->current()?->hubUrl);
    }

    public function testItUsesTheDockerHostForLoopbackTransportWithoutChangingTheEntity(): void
    {
        if (!is_file('/.dockerenv')) {
            self::markTestSkipped('Ce comportement ne s’applique que dans le conteneur Docker.');
        }

        $cipher = new CatalogSecretCipher('a-strong-test-application-secret');
        $configuration = new CatalogConfiguration(Uuid::fromString(self::INSTANCE_ID));
        $configuration->setHubUrl('http://127.0.0.1:8085');
        $configuration->prepareActivation($cipher);
        $configuration->markEnrolled(
            'source-42',
            'http://127.0.0.1:8085/webhooks/serenity/by-instance/' . self::INSTANCE_ID,
        );
        $store = $this->createStub(CatalogConfigurationStore::class);
        $store->method('get')->willReturn($configuration);

        $snapshot = new DoctrineCatalogConfigurationProvider($store, $cipher, true)->current();

        self::assertSame('http://host.docker.internal:8085', $snapshot?->hubUrl);
        self::assertSame(
            'http://host.docker.internal:8085/webhooks/serenity/by-instance/' . self::INSTANCE_ID,
            $snapshot?->webhookUrl,
        );
        self::assertSame('http://127.0.0.1:8085', $configuration->getHubUrl());
    }

    private function configuredEntity(CatalogSecretCipher $cipher): CatalogConfiguration
    {
        $configuration = new CatalogConfiguration(Uuid::fromString(self::INSTANCE_ID));
        $configuration->setHubUrl('https://hub.example');
        $configuration->prepareActivation($cipher);
        $configuration->applyHubAuthorization(
            'long-lived-enrollment-token',
            new \DateTimeImmutable('+1 year'),
            '019f8a68-1cbd-7504-9c1e-9c6d7fc8268d',
            'public-key-pem',
            'serenity-commerce-hub',
            'hub-main',
            $cipher,
        );

        return $configuration;
    }
}
