<?php

namespace Tests\App\Filters;

use App\Filters\ApiRateLimitFilter;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\URI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Test\CIUnitTestCase;
use Config\App;
use Config\Services;

class ApiRateLimitFilterTest extends CIUnitTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        Services::resetSingle('throttler');
        Services::resetSingle('session');
    }

    public function testBlocksRequestWhenThresholdIsExceeded(): void
    {
        $request = new IncomingRequest(config(App::class), new URI('https://example.test/api/health'), 'php://input', new UserAgent());
        $filter = new ApiRateLimitFilter();

        $first = $filter->before($request, [1, 60]);
        $second = $filter->before($request, [1, 60]);

        $this->assertNull($first);
        $this->assertInstanceOf(Response::class, $second);
        $this->assertSame(429, $second->getStatusCode());
    }
}
