<?php

use App\Models\Tenant;
use App\Support\Auth\Capabilities;
use App\Support\Rbac\UiEnforcement;
use Filament\Actions\Action;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('preflights bulk selections with a set-based tenant_memberships query (no N+1)', function () {
    $tenants = Tenant::factory()->count(25)->create();
    [$user] = createUserWithTenant($tenants->first(), role: 'owner');

    foreach ($tenants->slice(1) as $tenant) {
        $user->tenants()->syncWithoutDetaching([
            $tenant->getKey() => ['role' => 'owner'],
        ]);
    }

    $action = Action::make('test')->action(fn () => null);

    $enforcement = UiEnforcement::forAction($action)
        ->requireCapability(Capabilities::TENANT_SYNC);

    $membershipQueries = 0;

    DB::listen(function ($query) use (&$membershipQueries): void {
        if (str_contains($query->sql, 'tenant_memberships')) {
            $membershipQueries++;
        }
    });

    expect($enforcement->bulkSelectionIsAuthorized($user, $tenants))->toBeTrue();
    expect($membershipQueries)->toBe(1);
});
