<?php

use App\Models\ManagedEnvironment;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\TenantRole;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('does not execute additional managed_environment_memberships queries after first resolve within a request', function () {
    $tenant = ManagedEnvironment::factory()->create();

    [$user] = createUserWithTenant($tenant, role: TenantRole::Owner->value);

    $resolver = app(CapabilityResolver::class);

    $membershipSelects = 0;

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

    expect($resolver->can($user, $tenant, Capabilities::TENANT_VIEW))->toBeTrue();

    for ($i = 0; $i < 10; $i++) {
        expect($resolver->can($user, $tenant, Capabilities::TENANT_VIEW))->toBeTrue();
        expect($resolver->can($user, $tenant, Capabilities::PROVIDER_VIEW))->toBeTrue();
    }

    expect($membershipSelects)->toBe(1);
});
