<?php

use App\Http\Middleware\IpAccessControl;
use App\Models\User;
use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

beforeEach(function () {
    $ref = new ReflectionClass(SystemConfigService::class);
    $prop = $ref->getProperty('resolvedSettings');
    $prop->setAccessible(true);
    $prop->setValue(null, null);
    Cache::flush();

    Route::middleware([IpAccessControl::class])
        ->get('/__ip-probe', fn () => response('ok'))
        ->name('test.ip-probe');

    Route::middleware([IpAccessControl::class])
        ->get('/users/__ip-probe', fn () => response('ok-users'));
});

function setIpSetting(string $key, mixed $value): void
{
    app(SystemConfigService::class)->update([$key => $value]);
}

test('request passes through with no IP rules configured', function () {
    $this->get('/__ip-probe')->assertOk()->assertSeeText('ok');
});

test('blacklisted IP gets 403', function () {
    setIpSetting('ip_blacklist', '127.0.0.1, 10.0.0.5');

    $this->get('/__ip-probe', ['REMOTE_ADDR' => '127.0.0.1'])->assertForbidden();
});

test('non-blacklisted IP passes through', function () {
    setIpSetting('ip_blacklist', '10.0.0.5');

    $this->get('/__ip-probe', ['REMOTE_ADDR' => '127.0.0.1'])->assertOk();
});

test('admin whitelist denies non-whitelisted IPs on admin routes', function () {
    setIpSetting('ip_whitelist_admin', '203.0.113.1');

    $this->call('GET', '/users/__ip-probe', server: ['REMOTE_ADDR' => '127.0.0.1'])->assertForbidden();
});

test('admin whitelist permits whitelisted IPs on admin routes', function () {
    setIpSetting('ip_whitelist_admin', '127.0.0.1');

    $this->call('GET', '/users/__ip-probe', server: ['REMOTE_ADDR' => '127.0.0.1'])->assertOk();
});

test('admin whitelist does not affect non-admin routes', function () {
    setIpSetting('ip_whitelist_admin', '203.0.113.1');

    $this->get('/__ip-probe', ['REMOTE_ADDR' => '127.0.0.1'])->assertOk();
});

test('auto-blocked IP returns 429', function () {
    setIpSetting('auto_block_ip', true);
    Cache::put('ip_block:127.0.0.1', true, now()->addHour());

    $this->get('/__ip-probe', ['REMOTE_ADDR' => '127.0.0.1'])->assertStatus(429);
});

test('single session enforcement logs out stale session', function () {
    setIpSetting('session_single_session', true);
    $user = User::factory()->create(['last_session_id' => 'OTHER_SESSION_ID']);

    $this->actingAs($user)->get('/__ip-probe')
        ->assertRedirect(route('login', absolute: false));

    $this->assertGuest();
});
