<?php

declare(strict_types=1);

use App\Filament\Pages\Operations\TenantlessOperationRunViewer;
use App\Models\OperationRun;
use App\Support\Verification\VerificationReportFingerprint;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('redacts forbidden evidence fields in rendered verification reports', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'operator');
    $this->actingAs($user);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $report = json_decode(
        (string) file_get_contents(repo_path('specs/074-verification-checklist/contracts/examples/fail.json')),
        true,
        512,
        JSON_THROW_ON_ERROR,
    );

    $previousRun = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'failed',
        'context' => [
            'verification_report' => $report,
        ],
    ]);

    $report['checks'][0]['evidence'][] = ['kind' => 'authorization', 'value' => 'Bearer abc.def.ghi'];
    $report['checks'][0]['evidence'][] = ['kind' => 'access_token', 'value' => 'super-secret'];
    $report['checks'][0]['message'] = 'Authorization: Bearer abc.def.ghi access_token=super-secret';
    $report['previous_report_id'] = (int) $previousRun->getKey();

    $run = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'provider.connection.check',
        'status' => 'completed',
        'outcome' => 'failed',
        'context' => [
            'verification_report' => $report,
        ],
    ]);

    $fingerprint = VerificationReportFingerprint::forReport($report);

    assertNoOutboundHttp(function () use ($run, $fingerprint): void {
        Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run])
            ->assertSee('Verification report')
            ->assertSee('Open previous operation')
            ->assertSee($fingerprint)
            ->assertSee('Token acquisition works')
            ->assertDontSee('access_token')
            ->assertDontSee('Bearer abc.def.ghi')
            ->assertDontSee('super-secret');
    });
});
