<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Models\ManagedEnvironment;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Livewire\Livewire;
use Tests\Feature\Concerns\BuildsGovernanceArtifactTruthFixtures;

uses(BuildsGovernanceArtifactTruthFixtures::class);

it('renders blocked governance runs with explanation-first fallback copy when no artifact record exists', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $run = $this->makeArtifactTruthRun(
        tenant: $tenant,
        type: 'environment.review.compose',
        context: [
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'reason_code' => 'review_missing_sections',
        ],
        attributes: [
            'outcome' => 'blocked',
            'failure_summary' => [
                ['reason_code' => 'review_missing_sections', 'message' => 'The review basis is incomplete.'],
            ],
        ],
    );

    $truth = app(ArtifactTruthPresenter::class)->forOperationRun($run);
    $explanation = $truth->operatorExplanation;

    Filament::setTenant(null, true);
    $this->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]);
    session([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]);

    Livewire::actingAs($user)
        ->test(TenantlessOperationRunViewer::class, ['run' => $run])
        ->assertSee($explanation?->headline ?? '')
        ->assertSee($explanation?->nextActionText ?? '')
        ->assertSee('Artifact truth');
});
