<?php

use App\Filament\Resources\PolicyResource\Pages\ListPolicies;
use App\Jobs\SyncPoliciesJob;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

/**
 * Tests for US1: ManagedEnvironment member sees consistent disabled UX
 *
 * These tests verify that UiEnforcement correctly handles:
 * - Members WITH capability → action enabled, can execute
 * - Members WITHOUT capability → action visible but disabled with tooltip, cannot execute
 *
 * Note: In Filament v5, disabled actions don't throw 403 - they silently fail.
 * The server-side guard is a defense-in-depth measure that only triggers if
 * somehow the disabled check is bypassed.
 */
describe('US1: Member without capability sees disabled action + tooltip', function () {
    beforeEach(function () {
        Queue::fake();
    });

    it('shows sync action as visible but disabled for readonly members', function () {
        [$user, $tenant] = createUserWithTenant(role: 'readonly');
        $this->actingAs($user);

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

        Livewire::test(ListPolicies::class)
            ->assertActionVisible('sync')
            ->assertActionDisabled('sync');

        Queue::assertNothingPushed();
    });

    it('does not execute sync action for readonly members (silently blocked by Filament)', function () {
        [$user, $tenant] = createUserWithTenant(role: 'readonly');
        $this->actingAs($user);

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

        // When a disabled action is called, Filament blocks it silently (200 response, no execution)
        Livewire::test(ListPolicies::class)
            ->mountAction('sync')
            ->callMountedAction()
            ->assertSuccessful();

        // The action should NOT have executed
        Queue::assertNothingPushed();
    });
});

describe('US1: Member with capability sees enabled action + can execute', function () {
    beforeEach(function () {
        Queue::fake();
    });

    it('shows sync action as enabled for owner members', function () {
        bindFailHardGraphClient();

        [$user, $tenant] = createUserWithTenant(role: 'owner');
        $this->actingAs($user);

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

        Livewire::test(ListPolicies::class)
            ->assertActionVisible('sync')
            ->assertActionEnabled('sync');
    });

    it('allows owner members to execute sync action successfully', function () {
        bindFailHardGraphClient();

        [$user, $tenant] = createUserWithTenant(role: 'owner');
        $this->actingAs($user);

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

        Livewire::test(ListPolicies::class)
            ->mountAction('sync')
            ->callMountedAction()
            ->assertHasNoActionErrors();

        Queue::assertPushed(SyncPoliciesJob::class);
    });
});
