<?php
namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use Api\Core\RateLimiter\FileRateLimiter;

final class RateLimiterTest extends TestCase {
    private $dir;

    protected function setUp(): void {
        $this->dir = sys_get_temp_dir() . '/api_rate_limit_test';
        if (is_dir($this->dir)) {
            array_map('unlink', glob("$this->dir/*"));
        } else {
            mkdir($this->dir, 0700, true);
        }
    }

    public function testAllowsRequestsUnderLimit(): void {
        $limiter = new FileRateLimiter($this->dir);
        $key = 'test-client';
        $allowed = 0;
        for ($i = 0; $i < 5; $i++) {
            if ($limiter->allow($key)) $allowed++;
        }
        $this->assertGreaterThan(0, $allowed);
    }

    public function testBlocksWhenExceeded(): void {
        $requests = 5;
        $limiter = new FileRateLimiter($this->dir, $requests, 60);
        $key = 'test-client-2';
        
        for ($i = 0; $i < $requests; $i++) {
            $this->assertTrue($limiter->allow($key));
        }
        $this->assertFalse($limiter->allow($key));
    }
}
