<?php

declare(strict_types=1);

use App\Models\Finding;
use App\Services\Evidence\Sources\FindingsSummarySource;

it('derives descriptor-first source taxonomy for findings and summaries', function (): void {
    [$user, $tenant] = createUserWithTenant(ensureDefaultMicrosoftProviderConnection: true);
    $connection = $tenant->providerConnections()->where('provider', 'microsoft')->where('is_default', true)->firstOrFail();

    $finding = Finding::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
        'subject_external_id' => 'device-compliance-policy-1',
        'evidence_jsonb' => [
            'provider_key' => 'microsoft',
            'provider_connection_id' => (int) $connection->getKey(),
            'policy_type' => 'deviceCompliancePolicy',
            'policy_id' => 'device-compliance-policy-1',
        ],
    ]);

    $descriptor = $finding->artifactSourceDescriptor()->toArray();
    $providerDetail = $finding->artifactProviderDetail()->toArray();

    expect($descriptor)->toMatchArray([
        'workspace_id' => (int) $tenant->workspace_id,
        'tenant_id' => (int) $tenant->getKey(),
        'managed_environment_id' => (int) $tenant->getKey(),
        'source_family' => 'finding',
        'source_kind' => 'model_summary',
        'provider_key' => 'microsoft',
        'provider_connection_id' => (int) $connection->getKey(),
        'source_target_kind' => 'governed_subject',
        'source_target_identifier' => 'device-compliance-policy-1',
        'detector_key' => 'intune.device_compliance_policy',
        'control_key' => 'endpoint_hardening_compliance',
        'package_run_id' => null,
    ])
        ->and($descriptor)->not->toHaveKeys(['finding_type', 'policy_type', 'report_type'])
        ->and($providerDetail)->toMatchArray([
            'legacy_finding_type' => Finding::FINDING_TYPE_DRIFT,
            'legacy_policy_type' => 'deviceCompliancePolicy',
            'provider_object_type' => 'deviceCompliancePolicy',
            'provider_display_type' => 'Device Compliance',
        ]);

    $summary = app(FindingsSummarySource::class)->collect($tenant);
    $entry = collect($summary['summary_payload']['entries'])->firstWhere('id', (int) $finding->getKey());

    expect($entry['source_descriptor'])->toMatchArray($descriptor)
        ->and($entry['provider_detail'])->toMatchArray($providerDetail)
        ->and($entry['control_key'])->toBe('endpoint_hardening_compliance');

    $this->actingAs($user);
});
