<?php

use App\Support\Auth\Capabilities;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;

it('logs structured context on authorization denials without secrets', function () {
    Log::spy();

    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $gate = Gate::forUser($user);

    expect($gate->allows(Capabilities::TENANT_MANAGE, $tenant))->toBeFalse();
    expect($gate->allows(Capabilities::TENANT_MANAGE, $tenant))->toBeFalse();

    Log::shouldHaveReceived('warning')
        ->withArgs(function (string $message, array $context) use ($tenant, $user): bool {
            if ($message !== 'rbac.denied') {
                return false;
            }

            return ($context['capability'] ?? null) === Capabilities::TENANT_MANAGE
                && ($context['managed_environment_id'] ?? null) === (int) $tenant->getKey()
                && ($context['actor_user_id'] ?? null) === (int) $user->getKey();
        })
        ->once();
});
