<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class VerificationReportTenantlessTest extends TestCase
{
    use RefreshDatabase;

    public function test_renders_verification_report_on_canonical_detail_without_filament_tenant_context(): void
    {
        [$user, $tenant] = createUserWithTenant(role: 'operator');

        $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([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'user_id' => (int) $user->getKey(),
            'type' => 'provider.connection.check',
            'status' => 'completed',
            'outcome' => 'failed',
            'context' => [
                'verification_report' => $report,
            ],
        ]);

        $report['previous_report_id'] = (int) $previousRun->getKey();

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

        Filament::setTenant(null, true);

        $this->actingAs($user)
            ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
            ->get(\App\Support\OperationRunLinks::tenantlessView($run))
            ->assertOk()
            ->assertSee('Verification report')
            ->assertDontSee('Verification report unavailable')
            ->assertSee('Open previous operation')
            ->assertSee(\App\Support\OperationRunLinks::tenantlessView($previousRun), false)
            ->assertSee('Token acquisition works');
    }
}
