<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\Ui\GovernanceArtifactTruth\ArtifactTruthPresenter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Feature\Concerns\BuildsGovernanceArtifactTruthFixtures;

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

it('reuses governance operator explanations for run failure detail and next-step guidance', 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;

    expect($explanation)->not->toBeNull()
        ->and(OperationUxPresenter::surfaceFailureDetail($run))->toBe($explanation?->dominantCauseExplanation)
        ->and(OperationUxPresenter::surfaceGuidance($run))->toContain((string) $explanation?->nextActionText);
});
