<?php

declare(strict_types=1);

use App\Filament\Resources\BaselineSnapshotResource;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Services\Baselines\SnapshotRendering\RenderedSnapshotItem;
use App\Services\Baselines\SnapshotRendering\Renderers\FallbackSnapshotTypeRenderer;
use App\Services\Baselines\SnapshotRendering\SnapshotTypeRendererRegistry;

it('shows reference-only fidelity and explicit gap messaging for metadata-backed items', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
    ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
        'summary_jsonb' => [
            'total_items' => 1,
            'policy_type_counts' => ['deviceCompliancePolicy' => 1],
            'fidelity_counts' => ['content' => 0, 'meta' => 1],
            'gaps' => ['count' => 1, 'by_reason' => ['meta_fallback' => 1]],
        ],
    ]);

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'policy_type' => 'deviceCompliancePolicy',
        'subject_key' => 'bitlocker require',
        'subject_external_id' => hash('sha256', 'deviceCompliancePolicy|bitlocker require'),
        'meta_jsonb' => [
            'display_name' => 'Bitlocker Require',
            'platform' => 'windows',
            'warnings' => ['Only inventory metadata was available.'],
            'evidence' => [
                'fidelity' => 'meta',
                'source' => 'inventory',
                'observed_at' => '2026-03-09T12:00:00+00:00',
            ],
        ],
    ]);

    $this->actingAs($user)
        ->get(BaselineSnapshotResource::getUrl('view', ['record' => $snapshot], panel: 'admin'))
        ->assertOk()
        ->assertSeeInOrder(['Outcome summary', 'Coverage summary', 'Captured governed subjects', 'Technical detail'])
        ->assertSee('Snapshot status')
        ->assertSee('Reference only')
        ->assertSee('Inventory metadata')
        ->assertSee('Metadata-only evidence was captured for this item.')
        ->assertSee('Only inventory metadata was available.')
        ->assertDontSee('Artifact truth');
});

it('isolates renderer failures per group and falls back without breaking the page', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
    ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
        'summary_jsonb' => [
            'total_items' => 1,
            'policy_type_counts' => ['deviceCompliancePolicy' => 1],
            'fidelity_counts' => ['content' => 1, 'meta' => 0],
            'gaps' => ['count' => 0, 'by_reason' => []],
        ],
    ]);

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'policy_type' => 'deviceCompliancePolicy',
        'subject_key' => 'bitlocker require',
        'subject_external_id' => hash('sha256', 'deviceCompliancePolicy|bitlocker require'),
        'meta_jsonb' => [
            'display_name' => 'Bitlocker Require',
            'platform' => 'windows',
            'evidence' => [
                'fidelity' => 'content',
                'source' => 'policy_version',
                'observed_at' => '2026-03-09T12:00:00+00:00',
            ],
        ],
    ]);

    $throwingRenderer = new class extends FallbackSnapshotTypeRenderer
    {
        public function supports(string $policyType): bool
        {
            return $policyType === 'deviceCompliancePolicy';
        }

        public function render(BaselineSnapshotItem $item): RenderedSnapshotItem
        {
            throw new RuntimeException('Renderer exploded.');
        }
    };

    app()->instance(SnapshotTypeRendererRegistry::class, new SnapshotTypeRendererRegistry(
        renderers: [$throwingRenderer],
        fallbackRenderer: new FallbackSnapshotTypeRenderer,
    ));

    $this->actingAs($user)
        ->get(BaselineSnapshotResource::getUrl('view', ['record' => $snapshot], panel: 'admin'))
        ->assertOk()
        ->assertSee('Technical detail')
        ->assertSee('Structured rendering failed for this governed subject family. Fallback metadata is shown instead.')
        ->assertSee('Bitlocker Require')
        ->assertSee('A fallback renderer is being used for this item.');
});
