<?php

declare(strict_types=1);

use App\Filament\Pages\Monitoring\EvidenceOverview;
use App\Models\EvidenceSnapshot;
use App\Support\Evidence\EvidenceCompletenessState;
use App\Support\Evidence\EvidenceSnapshotStatus;
use App\Support\Ui\DerivedState\DerivedStateFamily;
use App\Support\Ui\DerivedState\RequestScopedDerivedStateStore;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use App\Support\Ui\GovernanceArtifactTruth\SurfaceCompressionContext;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('reuses one artifact-truth resolution per active snapshot row on the evidence overview', function (): void {
    $tenant = \App\Models\ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

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

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

    Livewire::actingAs($user)
        ->test(EvidenceOverview::class)
        ->assertCountTableRecords(1)
        ->assertCanSeeTableRecords([(string) $snapshot->getKey()])
        ->assertSee($tenant->name)
        ->assertSee('Outcome');

    $truth = app(ArtifactTruthPresenter::class)->forEvidenceSnapshot($snapshot->fresh());
    $overviewOutcome = app(ArtifactTruthPresenter::class)->compressedOutcomeFor(
        $snapshot->fresh(),
        SurfaceCompressionContext::evidenceOverview(),
    );
    $detailOutcome = app(ArtifactTruthPresenter::class)->compressedOutcomeFor(
        $snapshot->fresh(),
        SurfaceCompressionContext::evidenceSnapshot(),
    );
    $store = app(RequestScopedDerivedStateStore::class);

    expect($store->countStored(
        DerivedStateFamily::ArtifactTruth,
        EvidenceSnapshot::class,
        (string) $snapshot->getKey(),
        'evidence_snapshot',
    ))->toBe(1)
        ->and($store->countStored(
            DerivedStateFamily::ArtifactTruth,
            EvidenceSnapshot::class,
            (string) $snapshot->getKey(),
            SurfaceCompressionContext::evidenceOverview()->cacheVariant(),
        ))->toBe(1)
        ->and($store->countStored(
            DerivedStateFamily::ArtifactTruth,
            EvidenceSnapshot::class,
            (string) $snapshot->getKey(),
            SurfaceCompressionContext::evidenceSnapshot()->cacheVariant(),
        ))->toBe(1)
        ->and($truth->primaryLabel)->not->toBe('')
        ->and($overviewOutcome?->decisionDirection)->toBe($detailOutcome?->decisionDirection)
        ->and($overviewOutcome?->surfaceFamily)->toBe('evidence_overview')
        ->and($detailOutcome?->surfaceFamily)->toBe('evidence_snapshot');
});

it('keeps the evidence overview deny-as-not-found for users outside the workspace boundary', function (): void {
    $workspaceTenant = \App\Models\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();
});
