<?php

use App\Models\Permission;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

beforeEach(function () {
    Cache::flush();

    Route::middleware(['web', 'auth', 'active-permission:probe'])
        ->get('/__probe', fn () => response('ok'))
        ->name('test.probe');
});

test('inactive permission returns 403 even when user has it', function () {
    Permission::firstOrCreate(['name' => 'probe', 'guard_name' => 'web', 'is_active' => false]);
    $user = User::factory()->create();
    $user->givePermissionTo('probe');

    $this->actingAs($user)->get('/__probe')->assertForbidden();
});

test('active permission allows the request through', function () {
    Permission::firstOrCreate(['name' => 'probe', 'guard_name' => 'web', 'is_active' => true]);
    $user = User::factory()->create();
    $user->givePermissionTo('probe');

    $this->actingAs($user)->get('/__probe')->assertOk()->assertSeeText('ok');
});

test('missing permission returns 403', function () {
    $user = User::factory()->create();

    $this->actingAs($user)->get('/__probe')->assertForbidden();
});

test('cache is consulted on subsequent hits', function () {
    Permission::firstOrCreate(['name' => 'probe', 'guard_name' => 'web', 'is_active' => true]);
    $user = User::factory()->create();
    $user->givePermissionTo('probe');

    $this->actingAs($user)->get('/__probe')->assertOk();

    expect(Cache::has('permission_status:probe'))->toBeTrue();
});
