<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\EvidenceOverview;
use App\Filament\Resources\EvidenceSnapshotResource;
use App\Models\EvidenceSnapshot;
use App\Models\ManagedEnvironment;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Feature\Concerns\BuildsGovernanceArtifactTruthFixtures;

uses(RefreshDatabase::class, BuildsGovernanceArtifactTruthFixtures::class);

it('shows only authorized tenant rows on the workspace evidence overview', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
    $tenantB = ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenantA->workspace_id]);
    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $foreignWorkspaceTenant = ManagedEnvironment::factory()->create();

    foreach ([
        [$tenantA, EvidenceCompletenessState::Complete->value],
        [$tenantB, EvidenceCompletenessState::Partial->value],
        [$foreignWorkspaceTenant, EvidenceCompletenessState::Missing->value],
    ] as [$tenant, $state]) {
        EvidenceSnapshot::query()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'status' => EvidenceSnapshotStatus::Active->value,
            'completeness_state' => $state,
            'summary' => [
                'missing_dimensions' => $state === EvidenceCompletenessState::Missing->value ? 2 : 0,
                'stale_dimensions' => 0,
            ],
            'generated_at' => now(),
        ]);
    }

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(route('admin.evidence.overview'))
        ->assertOk()
        ->assertSee('Outcome')
        ->assertSee($tenantA->name)
        ->assertSee($tenantB->name)
        ->assertDontSee($foreignWorkspaceTenant->name)
        ->assertDontSee('Monitoring landing')
        ->assertDontSee('Navigation lane')
        ->assertDontSee('Focused review lane');
});

it('returns 404 for users without workspace membership on the evidence overview', function (): void {
    $workspaceTenant = ManagedEnvironment::factory()->create();
    $user = App\Models\User::factory()->create();

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceTenant->workspace_id])
        ->get(route('admin.evidence.overview'))
        ->assertNotFound();
});

it('applies the entitled tenant prefilter on the workspace evidence overview', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');
    $tenantB = ManagedEnvironment::factory()->create(['workspace_id' => (int) $tenantA->workspace_id]);
    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $snapshots = [];

    foreach ([[$tenantA, EvidenceCompletenessState::Complete->value], [$tenantB, EvidenceCompletenessState::Partial->value]] as [$tenant, $state]) {
        $snapshots[(int) $tenant->getKey()] = EvidenceSnapshot::query()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'status' => EvidenceSnapshotStatus::Active->value,
            'completeness_state' => $state,
            'summary' => ['missing_dimensions' => 0, 'stale_dimensions' => 0],
            'generated_at' => now(),
        ]);
    }

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
        ->get(route('admin.evidence.overview', ['environment_id' => (int) $tenantB->getKey()]))
        ->assertOk()
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshots[(int) $tenantB->getKey()]], tenant: $tenantB, panel: 'admin'), false)
        ->assertDontSee(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshots[(int) $tenantA->getKey()]], tenant: $tenantA, panel: 'admin'), false);
});

it('shows stale evidence burden and a create-review next step on the overview', function (): void {
    $staleTenant = ManagedEnvironment::factory()->create(['name' => 'Stale ManagedEnvironment']);
    [$user, $staleTenant] = createUserWithTenant(tenant: $staleTenant, role: 'owner');

    $freshTenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $staleTenant->workspace_id,
        'name' => 'Fresh ManagedEnvironment',
    ]);
    createUserWithTenant(tenant: $freshTenant, user: $user, role: 'owner');

    $staleSnapshot = $this->makeStaleArtifactTruthEvidenceSnapshot($staleTenant);
    $freshSnapshot = $this->makeArtifactTruthEvidenceSnapshot($freshTenant);

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $staleTenant->workspace_id])
        ->get(route('admin.evidence.overview'))
        ->assertOk()
        ->assertSee($staleTenant->name)
        ->assertSee($freshTenant->name)
        ->assertSee('Refresh the stale evidence before relying on this snapshot')
        ->assertSee('Create a current review from this evidence snapshot')
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $staleSnapshot], tenant: $staleTenant, panel: 'admin'), false)
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $freshSnapshot], tenant: $freshTenant, panel: 'admin'), false);
});

it('seeds the native entitled-tenant prefilter once and clears it through the page action', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);
    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $snapshotA = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'workspace_id' => (int) $tenantA->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'completeness_state' => EvidenceCompletenessState::Complete->value,
        'summary' => ['missing_dimensions' => 0, 'stale_dimensions' => 0],
        'generated_at' => now(),
    ]);

    $snapshotB = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $tenantB->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'completeness_state' => EvidenceCompletenessState::Partial->value,
        'summary' => ['missing_dimensions' => 1, 'stale_dimensions' => 0],
        'generated_at' => now(),
    ]);

    $this->actingAs($user);
    setAdminPanelContext();
    Filament::setTenant(null, true);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);

    $component = Livewire::withQueryParams([
        'environment_id' => (string) $tenantB->getKey(),
        'search' => $tenantB->name,
    ])->test(EvidenceOverview::class);

    $component
        ->assertSet('tableFilters.managed_environment_id.value', (string) $tenantB->getKey())
        ->assertSet('tableSearch', $tenantB->name)
        ->assertCanSeeTableRecords([(string) $snapshotB->getKey()])
        ->assertCanNotSeeTableRecords([(string) $snapshotA->getKey()]);

    $component
        ->callAction('clear_filters')
        ->assertRedirect(route('admin.evidence.overview'));

    $this->get(route('admin.evidence.overview'))
        ->assertOk()
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshotA], tenant: $tenantA, panel: 'admin'), false)
        ->assertSee(EvidenceSnapshotResource::getUrl('view', ['record' => $snapshotB], tenant: $tenantB, panel: 'admin'), false);
});
