<?php

declare(strict_types=1);

namespace Tests\Unit;

use Tests\Support\QdbTestCase;

final class LoginRateLimitTest extends QdbTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        require_once dirname(__DIR__, 2) . '/lib/login_rate_limit.php';
        $_SERVER['REMOTE_ADDR'] = '10.0.0.50';
    }

    public function testAllowsUnderLimit(): void
    {
        $settings = [
            'login_max_attempts'    => 3,
            'login_window_seconds'  => 300,
            'login_lockout_seconds' => 600,
        ];
        [$ok, $retry] = qdb_login_rate_limit_check('user_a', $settings);
        $this->assertTrue($ok);
        $this->assertSame(0, $retry);
    }

    public function testLocksAfterMaxFailures(): void
    {
        $settings = [
            'login_max_attempts'    => 2,
            'login_window_seconds'  => 300,
            'login_lockout_seconds' => 600,
        ];
        $user = 'lock_test_' . bin2hex(random_bytes(4));
        qdb_login_rate_limit_record_failure($user, $settings);
        qdb_login_rate_limit_record_failure($user, $settings);
        [$ok, $retry] = qdb_login_rate_limit_check($user, $settings);
        $this->assertFalse($ok);
        $this->assertGreaterThan(0, $retry);
    }

    public function testClearResetsCounter(): void
    {
        $settings = [
            'login_max_attempts'    => 1,
            'login_window_seconds'  => 300,
            'login_lockout_seconds' => 600,
        ];
        $user = 'clear_test_' . bin2hex(random_bytes(4));
        qdb_login_rate_limit_record_failure($user, $settings);
        qdb_login_rate_limit_clear($user);
        [$ok,] = qdb_login_rate_limit_check($user, $settings);
        $this->assertTrue($ok);
    }
}
