<?php

declare(strict_types=1);

use App\Filament\Resources\ManagedEnvironmentResource\Pages\EditManagedEnvironment;
use App\Filament\Resources\ManagedEnvironmentResource\RelationManagers\ManagedEnvironmentMembershipsRelationManager;
use App\Models\ManagedEnvironment;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

describe('ManagedEnvironment memberships relation manager UI enforcement', function () {
    it('shows membership actions as visible but disabled for operator members', function () {
        $tenant = ManagedEnvironment::factory()->create();
        [$user] = createUserWithTenant(tenant: $tenant, role: 'operator', workspaceRole: 'operator');

        $this->actingAs($user);
        $tenant->makeCurrent();
        Filament::setTenant($tenant, true);

        $otherUser = User::factory()->create();
        createUserWithTenant(tenant: $tenant, user: $otherUser, role: 'readonly');

        Livewire::test(ManagedEnvironmentMembershipsRelationManager::class, [
            'ownerRecord' => $tenant,
            'pageClass' => EditManagedEnvironment::class,
        ])
            ->assertTableActionVisible('add_member')
            ->assertTableActionDisabled('add_member')
            ->assertTableActionExists('add_member', function (Action $action): bool {
                return $action->getTooltip() === 'You do not have permission to manage environment access scopes.';
            })
            ->assertTableActionVisible('remove')
            ->assertTableActionDisabled('remove')
            ->assertTableActionExists('remove', function (Action $action): bool {
                return $action->getTooltip() === 'You do not have permission to manage environment access scopes.';
            });
    });
});
