<?php

declare(strict_types=1);

use App\Models\EvidenceSnapshot;
use App\Models\Finding;
use App\Models\StoredReport;
use App\Services\Evidence\EvidenceSnapshotService;
use App\Support\Evidence\EvidenceSnapshotStatus;

it('carries artifact source descriptors through evidence snapshot payloads and items', function (): void {
    [$user, $tenant] = createUserWithTenant(ensureDefaultMicrosoftProviderConnection: true);
    $connection = $tenant->providerConnections()->where('provider', 'microsoft')->where('is_default', true)->firstOrFail();

    StoredReport::factory()->permissionPosture()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'fingerprint' => 'permission-report-fingerprint',
        'payload' => [
            'provider_key' => 'microsoft',
            'provider_connection_id' => (int) $connection->getKey(),
            'posture_score' => 90,
            'required_count' => 4,
            'granted_count' => 4,
        ],
    ]);

    Finding::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'evidence_jsonb' => ['policy_type' => 'deviceCompliancePolicy'],
    ]);

    $payload = app(EvidenceSnapshotService::class)->buildSnapshotPayload($tenant);
    $permissionItem = collect($payload['items'])->firstWhere('dimension_key', 'permission_posture');

    expect($permissionItem['source_descriptor'])->toMatchArray([
        'workspace_id' => (int) $tenant->workspace_id,
        'tenant_id' => (int) $tenant->getKey(),
        'managed_environment_id' => (int) $tenant->getKey(),
        'source_family' => 'stored_report',
        'source_kind' => 'stored_report',
        'provider_key' => 'microsoft',
        'provider_connection_id' => (int) $connection->getKey(),
        'source_target_kind' => 'managed_environment',
        'source_target_identifier' => (string) $tenant->getKey(),
        'control_key' => 'strong_authentication',
        'package_run_id' => null,
    ])
        ->and($permissionItem['summary_payload']['source_descriptor'])->toMatchArray($permissionItem['source_descriptor'])
        ->and($payload['summary']['dimensions'])->each->toHaveKey('source_descriptor');

    $snapshot = EvidenceSnapshot::query()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'status' => EvidenceSnapshotStatus::Active->value,
        'fingerprint' => $payload['fingerprint'],
        'completeness_state' => $payload['completeness'],
        'summary' => $payload['summary'],
        'generated_at' => now(),
    ]);

    foreach ($payload['items'] as $item) {
        $snapshot->items()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            'dimension_key' => $item['dimension_key'],
            'state' => $item['state'],
            'required' => $item['required'],
            'source_kind' => $item['source_kind'],
            'source_record_type' => $item['source_record_type'],
            'source_record_id' => $item['source_record_id'],
            'source_fingerprint' => $item['source_fingerprint'],
            'measured_at' => $item['measured_at'],
            'freshness_at' => $item['freshness_at'],
            'summary_payload' => $item['summary_payload'],
            'sort_order' => $item['sort_order'],
        ]);
    }

    $persistedPermissionItem = $snapshot->items()->where('dimension_key', 'permission_posture')->firstOrFail();

    expect($persistedPermissionItem->artifactSourceDescriptor()->toArray())
        ->toMatchArray($permissionItem['source_descriptor']);

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