<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Models\OperationRun;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\Ui\DerivedState\DerivedStateFamily;
use App\Support\Ui\DerivedState\RequestScopedDerivedStateStore;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('reuses operation guidance and explanation state on the canonical run detail surface', function (): void {
    $tenant = \App\Models\ManagedEnvironment::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'baseline_compare',
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Blocked->value,
        'context' => [
            'reason_code' => 'missing_capability',
            'blocked_by' => 'queued_execution_legitimacy',
            'execution_legitimacy' => [
                'reason_code' => 'missing_capability',
            ],
        ],
        'failure_summary' => [[
            'code' => 'operation.blocked',
            'reason_code' => 'missing_capability',
            'message' => 'Operation blocked because the initiating actor no longer has the required capability.',
        ]],
    ]);

    Filament::setTenant(null, true);
    $this->actingAs($user)->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('Blocked by prerequisite')
        ->assertSee('Execution legitimacy revalidation');

    $guidance = OperationUxPresenter::surfaceGuidance($run->fresh());
    $operatorExplanation = OperationUxPresenter::governanceOperatorExplanation($run->fresh());
    $store = app(RequestScopedDerivedStateStore::class);

    expect($store->countStored(
        DerivedStateFamily::OperationUxGuidance,
        OperationRun::class,
        (string) $run->getKey(),
        'surface_guidance',
    ))->toBe(1)
        ->and($store->countStored(
            DerivedStateFamily::OperationUxExplanation,
            OperationRun::class,
            (string) $run->getKey(),
            'governance_operator_explanation',
        ))->toBe(1)
        ->and($guidance)->toBe('Review workspace or tenant access before retrying.')
        ->and($operatorExplanation?->headline)->not->toBe('');
});
