<?php

declare(strict_types=1);

use App\Filament\Resources\BaselineSnapshotResource;
use App\Filament\Resources\FindingResource;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\Finding;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Support\Navigation\CrossResourceNavigationMatrix;
use App\Support\Navigation\RelatedNavigationResolver;
use Filament\Facades\Filament;

it('renders finding related context and list drill-down links', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

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

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'display_name' => 'Windows Lockdown',
    ]);

    $version = PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'version_number' => 3,
    ]);

    $run = OperationRun::factory()->for($tenant)->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'baseline_compare',
    ]);

    $finding = Finding::factory()->for($tenant)->create([
        'current_operation_run_id' => (int) $run->getKey(),
        'evidence_jsonb' => [
            'current' => [
                'policy_version_id' => (int) $version->getKey(),
            ],
            'provenance' => [
                'baseline_profile_id' => (int) $profile->getKey(),
                'baseline_snapshot_id' => (int) $snapshot->getKey(),
                'compare_operation_run_id' => (int) $run->getKey(),
            ],
        ],
    ]);

    $relatedEntries = app(RelatedNavigationResolver::class)
        ->detailEntries(CrossResourceNavigationMatrix::SOURCE_FINDING, $finding);

    $primaryAction = app(RelatedNavigationResolver::class)
        ->primaryListAction(CrossResourceNavigationMatrix::SOURCE_FINDING, $finding);

    $this->get(FindingResource::getUrl('view', ['record' => $finding], tenant: $tenant))
        ->assertOk()
        ->assertSee('Related context')
        ->assertSee('Snapshot')
        ->assertSee(BaselineSnapshotResource::getUrl('view', ['record' => $snapshot], panel: 'admin'), false)
        ->assertSee(e($relatedEntries[1]['targetUrl']), false);

    $this->get(FindingResource::getUrl('index', tenant: $tenant))
        ->assertOk()
        ->assertSee($primaryAction?->actionLabel ?? '')
        ->assertSee($primaryAction?->targetUrl ?? '', false);
});
