<?php

namespace Velis\Test;

use PHPUnit\Framework\TestCase;
use Velis\Crypt\Crypt;

class CryptTest extends TestCase
{
    private Crypt $crypt;

    protected function setUp(): void
    {
        $this->crypt = new Crypt(key: base64_decode('yigi/kBqGgJMadex0Xsm8yKFgV2Om6iTsyYD7mBdHVY='));
    }

    public function testEncryptAndDecrypt(): void
    {
        // Given
        $dataToEncrypt = serialize([
            'name' => 'Baltazar Gąbka',
            'description' => 'Zażółć gęślą jaźń',
            'email' => 'bgabka@example.org',
        ]);

        // When encrypting
        $encrypted = $this->crypt->encrypt($dataToEncrypt);

        // Then
        self::assertNotEmpty($encrypted);
        self::assertIsString($encrypted);
        self::assertNotSame($dataToEncrypt, $encrypted);
        self::assertNotEquals(strlen($dataToEncrypt), strlen($encrypted));

        // When decrypting
        $decrypted = $this->crypt->decrypt($encrypted);

        // Then
        self::assertSame($dataToEncrypt, $decrypted);
    }

    public function testDecryptionWithLegacyMethodFallback(): void
    {
        // Given a string encrypted with the legacy method
        // "Hello, World!" encrypted with the legacy method
        // phpcs:ignore Generic.Files.LineLength.TooLong
        $dataLegacyEncrypted = 'NDhkMzkzNmMxMGUwYjA1Y2NhMjg5MDQyZWMzOTMxZTBlODkzYmY4ZWNjNTQyYTdjYWQ4MDcwZWZiZTU0YjQxOTwxLkuuWtUNm411xUKDJ4o8yOcty7NxFQLiI68dsCCB';

        // When decrypting with the new method
        $decrypted = $this->crypt->decrypt($dataLegacyEncrypted);

        // Then: expect that the string encrypted with the legacy method is decrypted correctly
        self::assertSame('Hello, World!', $decrypted);
    }
}
