<?php

use App\Filament\Resources\ProviderConnectionResource\Pages\ListProviderConnections;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Livewire\Livewire;

describe('Provider connections create action UI enforcement', function () {
    it('shows create action as visible but disabled for readonly members', function () {
        [$user, $tenant] = createUserWithTenant(role: 'readonly', fixtureProfile: 'provider-enabled');

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

        Livewire::withQueryParams(['environment_id' => (int) $tenant->getKey()])
            ->test(ListProviderConnections::class)
            ->assertActionVisible('create')
            ->assertActionDisabled('create')
            ->assertActionExists('create', function (Action $action): bool {
                return $action->getTooltip() === 'You do not have permission to create provider connections.';
            });
    });

    it('shows create action as enabled for owner members', function () {
        [$user, $tenant] = createUserWithTenant(role: 'owner', fixtureProfile: 'provider-enabled');

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

        Livewire::withQueryParams(['environment_id' => (int) $tenant->getKey()])
            ->test(ListProviderConnections::class)
            ->assertActionVisible('create')
            ->assertActionEnabled('create');
    });

    it('hides create action after membership is revoked mid-session', function () {
        [$user, $tenant] = createUserWithTenant(role: 'owner', fixtureProfile: 'provider-enabled');

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

        $component = Livewire::withQueryParams(['environment_id' => (int) $tenant->getKey()])
            ->test(ListProviderConnections::class)
            ->assertActionVisible('create')
            ->assertActionEnabled('create');

        $user->tenants()->detach($tenant->getKey());
        $user->workspaces()->detach((int) $tenant->workspace_id);
        app(\App\Services\Auth\CapabilityResolver::class)->clearCache();
        app(\App\Services\Auth\WorkspaceCapabilityResolver::class)->clearCache();

        $component
            ->call('$refresh')
            ->assertActionHidden('create');
    });
});
