<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use App\Core\CSRFProtection;

class CSRFProtectionTest extends TestCase
{
    protected function setUp(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION = [];
    }

    public function testGenerateToken(): void
    {
        $token = CSRFProtection::getToken();
        $this->assertNotEmpty($token);
        $this->assertEquals($token, CSRFProtection::getToken()); // نفس الـ token
    }

    public function testValidateToken(): void
    {
        $token = CSRFProtection::getToken();
        $this->assertTrue(CSRFProtection::validateToken($token));
        $this->assertFalse(CSRFProtection::validateToken('invalid_token'));
    }

    public function testGetTokenField(): void
    {
        $field = CSRFProtection::getTokenField();
        $this->assertStringContainsString('<input', $field);
        $this->assertStringContainsString('name="csrf_token"', $field);
    }

    public function testValidatePostRequest(): void
    {
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $_POST['csrf_token'] = CSRFProtection::getToken();
        $this->assertTrue(CSRFProtection::validatePostRequest());
        
        $_POST['csrf_token'] = 'invalid';
        $this->assertFalse(CSRFProtection::validatePostRequest());
    }

    public function testRegenerateToken(): void
    {
        $oldToken = CSRFProtection::getToken();
        CSRFProtection::regenerateToken();
        $newToken = CSRFProtection::getToken();
        $this->assertNotEquals($oldToken, $newToken);
    }
}
