<?php

declare(strict_types=1);

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

final class CryptoTest extends TestCase
{
    public function testAesRoundTrip(): void
    {
        $key = str_repeat('K', 32);
        $plain = '{"clients":[{"clientCode":"C1"}]}';
        $enc = aes256_cbc_encrypt_bytes($plain, $key);
        $this->assertGreaterThan(16, strlen($enc));
        $dec = aes256_cbc_decrypt_bytes($enc, $key);
        $this->assertSame($plain, $dec);
    }

    public function testHkdfDeterministicForToken(): void
    {
        $token = bin2hex(random_bytes(16));
        $k1 = hkdf_session_key_from_token($token);
        $k2 = hkdf_session_key_from_token($token);
        $this->assertSame(32, strlen($k1));
        $this->assertSame($k1, $k2);
    }

    public function testHkdfDiffersForDifferentTokens(): void
    {
        $a = hkdf_session_key_from_token(bin2hex(random_bytes(16)));
        $b = hkdf_session_key_from_token(bin2hex(random_bytes(16)));
        $this->assertNotSame($a, $b);
    }

    public function testDecryptFailsWithWrongKey(): void
    {
        $key = str_repeat('K', 32);
        $enc = aes256_cbc_encrypt_bytes('payload', $key);
        $this->expectException(\Exception::class);
        aes256_cbc_decrypt_bytes($enc, str_repeat('X', 32));
    }

    public function testDecryptFailsWhenCiphertextTampered(): void
    {
        $key = str_repeat('K', 32);
        $enc = aes256_cbc_encrypt_bytes('payload', $key);
        $enc[20] = $enc[20] === 'a' ? 'b' : 'a';
        $this->expectException(\Exception::class);
        aes256_cbc_decrypt_bytes($enc, $key);
    }
}
