<?php

declare(strict_types=1);

use App\Filament\Pages\Governance\GovernanceInbox;
use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Filament\Resources\EnvironmentReviewResource;
use App\Models\ManagedEnvironment;
use App\Support\EnvironmentReviewStatus;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('keeps the customer review workspace 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: $tenant, role: 'readonly');
    $snapshot = seedEnvironmentReviewEvidence($tenant);

    $review = composeEnvironmentReviewForTest($tenant, $user, $snapshot);
    $review->forceFill([
        'status' => EnvironmentReviewStatus::Published->value,
        'generated_at' => now(),
        'published_at' => now(),
        'published_by_user_id' => (int) $user->getKey(),
    ])->save();

    $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: 'review_follow_up',
        backLinkUrl: GovernanceInbox::getUrl(panel: 'admin', parameters: [
            'environment_id' => (string) $tenant->getKey(),
            'family' => 'review_follow_up',
        ]),
    );

    Livewire::withQueryParams(array_replace($context->toQuery(), [
        'environment_id' => (int) $tenant->getKey(),
    ]))
        ->actingAs($user)
        ->test(CustomerReviewWorkspace::class)
        ->assertSet('tableFilters.managed_environment_id.value', (string) $tenant->getKey())
        ->assertActionVisible('return_to_governance_inbox')
        ->assertCanSeeTableRecords([$tenant->fresh()])
        ->assertSee(EnvironmentReviewResource::environmentScopedUrl('view', ['record' => $review->fresh()], $tenant), false)
        ->assertSee(CustomerReviewWorkspace::DETAIL_CONTEXT_QUERY_KEY.'=1', false)
        ->assertSee('nav%5Bsource_surface%5D=governance.inbox', false)
        ->assertSee('nav%5Bfamily_key%5D=review_follow_up', false)
        ->assertDontSee('This workspace decision surface routes you');
});
