<?php

namespace Tests\Feature;

use App\Models\Setting;
use App\Services\BruteforceGuard;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class BruteforceGuardExemptTest extends TestCase
{
    use RefreshDatabase;

    private function guard(): BruteforceGuard
    {
        return app(BruteforceGuard::class);
    }

    public function test_loopback_and_ipv6_loopback_are_exempt(): void
    {
        $g = $this->guard();
        $this->assertTrue($g->isExempt('127.0.0.1'));
        $this->assertTrue($g->isExempt('::1'));
        $this->assertTrue($g->isExempt('0:0:0:0:0:0:0:1')); // alternate spelling
    }

    public function test_default_private_whitelist_is_exempt_public_is_not(): void
    {
        $g = $this->guard();
        $this->assertTrue($g->isExempt('192.168.4.20'));  // default whitelist
        $this->assertTrue($g->isExempt('10.9.9.9'));
        $this->assertFalse($g->isExempt('203.0.113.7'));   // public
    }

    public function test_invalid_ip_is_treated_as_exempt(): void
    {
        $this->assertTrue($this->guard()->isExempt('not-an-ip'));
    }

    public function test_custom_whitelist_cidr_matches(): void
    {
        Setting::put('bruteforce_whitelist', '203.0.113.0/24');
        $this->assertTrue($this->guard()->isExempt('203.0.113.50'));
        $this->assertFalse($this->guard()->isExempt('203.0.114.50'));
    }
}
