<?php

declare(strict_types=1);

use App\Filament\Pages\Findings\FindingsIntakeQueue;
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 findings intake 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 = Finding::factory()
        ->for($tenant)
        ->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'assignee_user_id' => null,
            'status' => Finding::STATUS_NEW,
            'subject_external_id' => 'intake-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: 'intake_findings',
        backLinkUrl: GovernanceInbox::getUrl(panel: 'admin', parameters: [
            'managed_environment_id' => (string) $tenant->getKey(),
            'family' => 'intake_findings',
        ]),
    );

    Livewire::withQueryParams(array_replace($context->toQuery(), [
        'tenant' => (string) $tenant->external_id,
        'view' => 'needs_triage',
    ]))
        ->actingAs($user)
        ->test(FindingsIntakeQueue::class)
        ->assertSet('tableFilters.managed_environment_id.value', (string) $tenant->getKey())
        ->assertActionVisible('return_to_governance_inbox')
        ->assertCanSeeTableRecords([$finding])
        ->assertSee('Shared unassigned work')
        ->assertDontSee('This workspace decision surface routes you');
});
