<?php

declare(strict_types=1);

use App\Filament\Pages\Findings\MyFindingsInbox;
use App\Filament\Pages\Governance\GovernanceInbox;
use App\Models\Finding;
use App\Models\ManagedEnvironment;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('keeps my findings secondary when opened from the governance inbox', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'name' => 'Alpha ManagedEnvironment',
        'external_id' => 'alpha-tenant',
    ]);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner', workspaceRole: 'owner');

    Finding::factory()
        ->for($tenant)
        ->assignedTo((int) $user->getKey())
        ->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'subject_external_id' => 'assigned-from-governance',
        ]);

    $this->actingAs($user);
    Filament::setCurrentPanel('admin');
    Filament::setTenant(null, true);
    Filament::bootCurrentPanel();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    $context = CanonicalNavigationContext::forGovernanceInbox(
        canonicalRouteName: GovernanceInbox::getRouteName(Filament::getPanel('admin')),
        tenantId: (int) $tenant->getKey(),
        familyKey: 'assigned_findings',
        backLinkUrl: GovernanceInbox::getUrl(panel: 'admin', parameters: [
            'managed_environment_id' => (string) $tenant->getKey(),
            'family' => 'assigned_findings',
        ]),
    );

    Livewire::withQueryParams(array_replace($context->toQuery(), [
        'tenant' => (string) $tenant->external_id,
    ]))
        ->actingAs($user)
        ->test(MyFindingsInbox::class)
        ->assertSet('tableFilters.managed_environment_id.value', (string) $tenant->getKey())
        ->assertActionVisible('return_to_governance_inbox')
        ->assertCanSeeTableRecords([Finding::query()->where('subject_external_id', 'assigned-from-governance')->firstOrFail()])
        ->assertSee('Assigned to me only')
        ->assertDontSee('This workspace decision surface routes you');
});
