<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use App\Core\RateLimiter;
use App\Core\Database;

class RateLimiterTest extends TestCase
{
    private \PDO $db;
    private RateLimiter $rateLimiter;

    protected function setUp(): void
    {
        $config = require __DIR__ . '/../../config/config.php';
        $this->db = Database::getInstance($config['db'])->connection();
        $this->rateLimiter = new RateLimiter($this->db);
        
        // تنظيف البيانات قبل كل اختبار
        $this->db->exec("DELETE FROM rate_limit_logs WHERE identifier LIKE 'test_%'");
    }

    protected function tearDown(): void
    {
        $this->db->exec("DELETE FROM rate_limit_logs WHERE identifier LIKE 'test_%'");
    }

    public function testCheckRateLimit(): void
    {
        $identifier = 'test_user_' . time();
        
        // أول 5 محاولات يجب أن تمر
        for ($i = 0; $i < 5; $i++) {
            $this->assertTrue($this->rateLimiter->check('login', $identifier, 5, 60));
        }
        
        // المحاولة السادسة يجب أن تفشل
        $this->assertFalse($this->rateLimiter->check('login', $identifier, 5, 60));
    }

    public function testRecordAttempt(): void
    {
        $identifier = 'test_user_' . time();
        $this->rateLimiter->recordAttempt('login', $identifier);
        
        $stmt = $this->db->prepare("SELECT attempts FROM rate_limit_logs WHERE action = ? AND identifier = ?");
        $stmt->execute(['login', $identifier]);
        $result = $stmt->fetch();
        
        $this->assertNotFalse($result);
        $this->assertEquals(1, $result['attempts']);
    }

    public function testResetAttempts(): void
    {
        $identifier = 'test_user_' . time();
        
        // تسجيل محاولات
        for ($i = 0; $i < 3; $i++) {
            $this->rateLimiter->recordAttempt('login', $identifier);
        }
        
        // إعادة تعيين
        $this->rateLimiter->resetAttempts('login', $identifier);
        
        $stmt = $this->db->prepare("SELECT attempts FROM rate_limit_logs WHERE action = ? AND identifier = ?");
        $stmt->execute(['login', $identifier]);
        $result = $stmt->fetch();
        
        $this->assertFalse($result); // يجب أن يكون محذوفاً
    }
}
