<?php

declare(strict_types=1);

use App\Filament\Pages\Findings\MyFindingsInbox;
use App\Filament\Pages\Governance\GovernanceInbox;
use App\Models\Finding;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperationRunLinks;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;

it('embeds canonical governance inbox navigation context into source links', 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)
        ->assignedTo((int) $user->getKey())
        ->create();

    $run = OperationRun::factory()
        ->forTenant($tenant)
        ->create([
            'status' => OperationRunStatus::Completed->value,
            'outcome' => OperationRunOutcome::Failed->value,
            'completed_at' => now()->subMinute(),
        ]);

    $context = new CanonicalNavigationContext(
        sourceSurface: 'governance.inbox',
        canonicalRouteName: GovernanceInbox::getRouteName(Filament::getPanel('admin')),
        backLinkLabel: 'Back to governance inbox',
        backLinkUrl: GovernanceInbox::getUrl(panel: 'admin'),
    );

    $response = $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->get(GovernanceInbox::getUrl(panel: 'admin'));

    $response->assertOk();

    $expectedMyFindingsUrl = htmlspecialchars(
        MyFindingsInbox::getUrl(panel: 'admin').'?'.http_build_query($context->toQuery()),
        ENT_QUOTES,
    );
    $expectedOperationUrl = htmlspecialchars(
        OperationRunLinks::tenantlessView($run, $context),
        ENT_QUOTES,
    );

    $response->assertSee($expectedMyFindingsUrl, false)
        ->assertSee($expectedOperationUrl, false)
        ->assertSee((string) $finding->getKey())
        ->assertSee('nav%5Bback_label%5D=Back+to+governance+inbox', false);
});