<?php

declare(strict_types=1);

use App\Filament\Pages\Reviews\ReviewRegister;
use App\Models\ManagedEnvironment;
use App\Support\EnvironmentReviewStatus;
use App\Support\Workspaces\WorkspaceContext;
use Livewire\Livewire;

it('Spec314 review register ignores stale persisted environment filters on clean entry', function (): void {
    $environmentA = ManagedEnvironment::factory()->active()->create();
    [$user, $environmentA] = createUserWithTenant(tenant: $environmentA, role: 'readonly');

    $environmentB = ManagedEnvironment::factory()->active()->create([
        'workspace_id' => (int) $environmentA->workspace_id,
    ]);
    createUserWithTenant(tenant: $environmentB, user: $user, role: 'readonly');

    $reviewA = composeEnvironmentReviewForTest($environmentA, $user, seedEnvironmentReviewEvidence($environmentA));
    $reviewA->forceFill([
        'status' => EnvironmentReviewStatus::Published->value,
        'published_at' => now(),
        'published_by_user_id' => (int) $user->getKey(),
    ])->save();

    $reviewB = composeEnvironmentReviewForTest($environmentB, $user, seedEnvironmentReviewEvidence($environmentB));
    $reviewB->forceFill([
        'status' => EnvironmentReviewStatus::Published->value,
        'published_at' => now(),
        'published_by_user_id' => (int) $user->getKey(),
    ])->save();

    $this->actingAs($user);
    setAdminPanelContext();
    session()->put(WorkspaceContext::SESSION_KEY, (int) $environmentA->workspace_id);

    $component = Livewire::actingAs($user)->test(ReviewRegister::class);
    $filtersSessionKey = $component->instance()->getTableFiltersSessionKey();

    session()->put($filtersSessionKey, [
        'managed_environment_id' => ['value' => (string) $environmentA->getKey()],
    ]);

    Livewire::actingAs($user)
        ->test(ReviewRegister::class)
        ->assertCanSeeTableRecords([$reviewA->fresh(), $reviewB->fresh()]);

    expect(data_get(session()->get($filtersSessionKey, []), 'managed_environment_id.value'))->toBeNull();
});
