<?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 PHPUnit\Framework\TestCase;

final class CatalogSecretCipherTest extends TestCase
{
    private CatalogSecretCipher $cipher;

    protected function setUp(): void
    {
        $this->cipher = new CatalogSecretCipher('test-app-secret-with-sufficient-entropy');
    }

    public function testItEncryptsAndDecryptsASecretWithRandomizedAead(): void
    {
        $first = $this->cipher->encrypt('secret-value', CatalogSecretCipher::PURPOSE_ENROLLMENT_TOKEN);
        $second = $this->cipher->encrypt('secret-value', CatalogSecretCipher::PURPOSE_ENROLLMENT_TOKEN);

        self::assertNotSame($first, $second);
        self::assertStringNotContainsString('secret-value', $first);
        self::assertSame(
            'secret-value',
            $this->cipher->decrypt($first, CatalogSecretCipher::PURPOSE_ENROLLMENT_TOKEN),
        );
    }

    public function testItAuthenticatesTheSecretPurpose(): void
    {
        $envelope = $this->cipher->encrypt('secret-value', CatalogSecretCipher::PURPOSE_ENROLLMENT_TOKEN);

        $this->expectException(\RuntimeException::class);
        $this->cipher->decrypt($envelope, CatalogSecretCipher::PURPOSE_WEBHOOK_SECRET);
    }

    public function testItRejectsATamperedEnvelope(): void
    {
        $envelope = $this->cipher->encrypt('secret-value', CatalogSecretCipher::PURPOSE_WEBHOOK_SECRET);
        $lastCharacter = substr($envelope, -1);
        $tampered = substr($envelope, 0, -1) . ('A' === $lastCharacter ? 'B' : 'A');

        $this->expectException(\RuntimeException::class);
        $this->cipher->decrypt($tampered, CatalogSecretCipher::PURPOSE_WEBHOOK_SECRET);
    }

    public function testItRejectsAnEmptyApplicationSecret(): void
    {
        $this->expectException(\LogicException::class);
        new CatalogSecretCipher('')->encrypt('secret-value', CatalogSecretCipher::PURPOSE_WEBHOOK_SECRET);
    }
}
