<?php

declare(strict_types=1);

use App\Filament\Pages\Governance\GovernanceInbox;
use App\Models\Finding;
use App\Models\FindingException;
use App\Models\ManagedEnvironment;
use App\Support\Workspaces\WorkspaceContext;

it('launches the finding exceptions lane with tenant and family return context', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'name' => 'Alpha ManagedEnvironment',
        'external_id' => 'alpha-tenant',
    ]);
    [$user, $tenant] = createUserWithTenant($tenant, role: 'owner', workspaceRole: 'manager');

    $finding = Finding::factory()
        ->for($tenant)
        ->riskAccepted()
        ->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'subject_external_id' => 'governance-exception-lane',
        ]);

    $exception = FindingException::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'finding_id' => (int) $finding->getKey(),
        'requested_by_user_id' => (int) $user->getKey(),
        'owner_user_id' => (int) $user->getKey(),
        'status' => FindingException::STATUS_PENDING,
        'current_validity_state' => FindingException::VALIDITY_MISSING_SUPPORT,
        'request_reason' => 'Governance convergence request',
        'requested_at' => now()->subDay(),
        'review_due_at' => now()->addDay(),
        'evidence_summary' => ['reference_count' => 0],
    ]);

    $response = $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(GovernanceInbox::getUrl(panel: 'admin').'?environment_id='.(string) $tenant->getKey().'&family=finding_exceptions');

    $response->assertOk()
        ->assertSee('Finding exceptions')
        ->assertSee('Open finding exceptions')
        ->assertSee('Governance convergence request')
        ->assertSee('nav%5Bfamily_key%5D=finding_exceptions', false)
        ->assertSee('nav%5Bback_url%5D='.urlencode(GovernanceInbox::getUrl(panel: 'admin').'?environment_id='.(string) $tenant->getKey().'&family=finding_exceptions'), false)
        ->assertSee('exception='.(string) $exception->getKey(), false)
        ->assertDontSee('Open my findings')
        ->assertDontSee('Open findings intake');
});
