<?php

declare(strict_types=1);

use App\Services\Baselines\BaselineSnapshotItemNormalizer;

it('deduplicates snapshot items by subject reference and keeps the stronger evidence', function (): void {
    $normalizer = new BaselineSnapshotItemNormalizer;

    $result = $normalizer->deduplicate([
        [
            'subject_type' => 'policy',
            'subject_external_id' => 'subject-1',
            'subject_key' => 'standard',
            'policy_type' => 'deviceConfiguration',
            'baseline_hash' => 'hash-meta',
            'meta_jsonb' => [
                'evidence' => [
                    'fidelity' => 'meta',
                    'observed_at' => '2026-03-22T23:18:29+00:00',
                ],
            ],
        ],
        [
            'subject_type' => 'policy',
            'subject_external_id' => 'subject-1',
            'subject_key' => 'standard',
            'policy_type' => 'deviceConfiguration',
            'baseline_hash' => 'hash-content',
            'meta_jsonb' => [
                'evidence' => [
                    'fidelity' => 'content',
                    'observed_at' => '2026-03-22T23:18:30+00:00',
                ],
            ],
        ],
        [
            'subject_type' => 'policy',
            'subject_external_id' => 'subject-2',
            'subject_key' => 'unique',
            'policy_type' => 'deviceConfiguration',
            'baseline_hash' => 'hash-unique',
            'meta_jsonb' => [
                'evidence' => [
                    'fidelity' => 'content',
                    'observed_at' => '2026-03-22T23:18:31+00:00',
                ],
            ],
        ],
    ]);

    expect($result['duplicates'])->toBe(1)
        ->and($result['items'])->toHaveCount(2)
        ->and(collect($result['items'])->firstWhere('subject_external_id', 'subject-1'))
        ->toMatchArray([
            'baseline_hash' => 'hash-content',
            'subject_key' => 'standard',
        ]);
});
