<?php
namespace Tests\Unit\Shared\Security;

use PHPUnit\Framework\TestCase;
use Shared\Security\CsrfToken;

class CsrfTokenTest extends TestCase
{
    protected function setUp(): void
    {
        $_SESSION = [];
    }

    public function testGetTokenReturns64CharHexString(): void
    {
        $token = CsrfToken::getToken();
        $this->assertIsString($token);
        $this->assertSame(64, strlen($token));
        $this->assertMatchesRegularExpression('/^[0-9a-f]{64}$/', $token);
    }

    public function testGetTokenIsIdempotent(): void
    {
        $first = CsrfToken::getToken();
        $second = CsrfToken::getToken();
        $this->assertSame($first, $second);
    }

    public function testValidateReturnsTrueForCorrectToken(): void
    {
        $token = CsrfToken::getToken();
        $this->assertTrue(CsrfToken::validate($token));
    }

    public function testValidateReturnsFalseForEmptyString(): void
    {
        CsrfToken::getToken();
        $this->assertFalse(CsrfToken::validate(''));
    }

    public function testValidateReturnsFalseForWrongToken(): void
    {
        CsrfToken::getToken();
        $this->assertFalse(CsrfToken::validate('aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899'));
    }

    public function testValidateReturnsFalseWhenNoSessionToken(): void
    {
        $this->assertFalse(CsrfToken::validate('sometoken'));
    }

    public function testRegenerateChangesToken(): void
    {
        $before = CsrfToken::getToken();
        CsrfToken::regenerate();
        $after = CsrfToken::getToken();
        $this->assertNotSame($before, $after);
        $this->assertSame(64, strlen($after));
    }
}
