<?php

use App\Models\ManagedEnvironment;
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 managed_environment_memberships query (no N+1)', function () {
    $firstTenant = ManagedEnvironment::factory()->create();
    [$user, $firstTenant] = createUserWithTenant($firstTenant, role: 'owner');
    $tenants = collect([$firstTenant])->merge(
        ManagedEnvironment::factory()->count(24)->create([
            'workspace_id' => (int) $firstTenant->workspace_id,
        ])
    );

    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, 'managed_environment_memberships')) {
            $membershipQueries++;
        }
    });

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