<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Services\OperationRunService;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Providers\ProviderReasonCodes;

it('Spec081 stores blocked operation runs with sanitized reason and link-only next steps', function (): void {
    $tenant = ManagedEnvironment::factory()->create();
    $service = app(OperationRunService::class);

    $run = $service->ensureRunWithIdentity(
        tenant: $tenant,
        type: 'provider.connection.check',
        identityInputs: [
            'provider_connection_id' => 99,
        ],
        context: [
            'provider' => 'microsoft',
            'provider_connection_id' => 99,
            'target_scope' => [
                'entra_tenant_id' => $tenant->graphTenantId(),
            ],
        ],
    );

    $finalized = $service->finalizeBlockedRun(
        run: $run,
        reasonCode: ProviderReasonCodes::ProviderCredentialMissing,
        nextSteps: [
            ['label' => 'Update Credentials', 'url' => '/admin/provider-connections?environment_id=123'],
            ['label' => '', 'url' => '/invalid'],
        ],
        message: 'client_secret=super-secret',
    );

    $finalized->refresh();

    expect($finalized->status)->toBe(OperationRunStatus::Completed->value)
        ->and($finalized->outcome)->toBe(OperationRunOutcome::Blocked->value)
        ->and($finalized->context['reason_code'] ?? null)->toBe(ProviderReasonCodes::ProviderCredentialMissing)
        ->and(data_get($finalized->context, 'reason_translation.operator_label'))->toBe('Credentials missing')
        ->and(data_get($finalized->context, 'reason_translation.short_explanation'))->toContain('credentials required to authenticate')
        ->and($finalized->context['next_steps'] ?? [])->toBe([
            ['label' => 'Update Credentials', 'url' => '/admin/provider-connections?environment_id=123'],
        ])
        ->and($finalized->failure_summary[0]['reason_code'] ?? null)->toBe(ProviderReasonCodes::ProviderCredentialMissing)
        ->and((string) ($finalized->failure_summary[0]['message'] ?? ''))->not->toContain('secret');
});
