<?php

declare(strict_types=1);

use App\Filament\Pages\Reviews\ReviewRegister;
use App\Models\EnvironmentReview;
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 Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('reuses one artifact-truth resolution per row on the canonical review register', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $review = composeEnvironmentReviewForTest($tenant, $user);

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

    Livewire::actingAs($user)
        ->test(ReviewRegister::class)
        ->assertCanSeeTableRecords([$review])
        ->assertSee('Outcome')
        ->assertSee('Next step');

    $truth = app(ArtifactTruthPresenter::class)->forEnvironmentReview($review->fresh());
    $registerOutcome = app(ArtifactTruthPresenter::class)->compressedOutcomeFor(
        $review->fresh(),
        SurfaceCompressionContext::reviewRegister(),
    );
    $detailOutcome = app(ArtifactTruthPresenter::class)->compressedOutcomeFor(
        $review->fresh(),
        SurfaceCompressionContext::environmentReview(),
    );
    $store = app(RequestScopedDerivedStateStore::class);

    expect($store->countStored(
        DerivedStateFamily::ArtifactTruth,
        EnvironmentReview::class,
        (string) $review->getKey(),
        'environment_review',
    ))->toBe(1)
        ->and($store->countStored(
            DerivedStateFamily::ArtifactTruth,
            EnvironmentReview::class,
            (string) $review->getKey(),
            SurfaceCompressionContext::reviewRegister()->cacheVariant(),
        ))->toBe(1)
        ->and($store->countStored(
            DerivedStateFamily::ArtifactTruth,
            EnvironmentReview::class,
            (string) $review->getKey(),
            SurfaceCompressionContext::environmentReview()->cacheVariant(),
        ))->toBe(1)
        ->and($truth->primaryLabel)->not->toBe('')
        ->and($truth->nextStepText())->not->toBe('')
        ->and($registerOutcome?->decisionDirection)->toBe($detailOutcome?->decisionDirection)
        ->and($registerOutcome?->surfaceFamily)->toBe('review_register')
        ->and($detailOutcome?->surfaceFamily)->toBe('environment_review');
});
