<?php

declare(strict_types=1);

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

it('adds shared canonical control references to findings-derived evidence summaries', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    Finding::factory()->permissionPosture()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);
    Finding::factory()->entraAdminRoles()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);
    Finding::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'finding_type' => Finding::FINDING_TYPE_DRIFT,
        'evidence_jsonb' => [
            'policy_type' => 'deviceConfiguration',
        ],
    ]);

    $item = app(FindingsSummarySource::class)->collect($tenant);
    $summary = $item['summary_payload'];

    expect($summary['canonical_controls'])->toHaveCount(3)
        ->and(collect($summary['canonical_controls'])->pluck('control_key')->all())->toEqualCanonicalizing([
            'endpoint_hardening_compliance',
            'privileged_access_governance',
            'strong_authentication',
        ]);

    foreach ($summary['entries'] as $entry) {
        expect($entry['canonical_control_resolution']['status'])->toBe('resolved')
            ->and($entry['canonical_control_resolution']['control'])->toHaveKey('control_key')
            ->and($entry)->not->toHaveKey('control_label');
    }

    $payload = app(EvidenceSnapshotService::class)->buildSnapshotPayload($tenant);

    expect($payload['summary']['canonical_controls'])->toHaveCount(3);
});

it('keeps missing bindings explicit instead of inventing evidence fallback labels', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $summary = app(FindingsSummarySource::class)->collect($tenant)['summary_payload'];
    $entry = $summary['entries'][0];

    expect($entry['canonical_control_resolution'])->toMatchArray([
        'status' => 'unresolved',
        'reason_code' => 'missing_binding',
    ])->and($entry['canonical_control_resolution'])->not->toHaveKey('control')
        ->and($entry)->not->toHaveKey('control_label');
});
