<?php

use App\Jobs\CompareBaselineToTenantJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;

it('suppresses missing_policy outcomes for uncovered types and records coverage context', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'scope_jsonb' => [
            'policy_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
            'foundation_types' => [],
        ],
    ]);

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

    $profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);

    $coveredExternalId = 'covered-uuid';
    $coveredDisplayName = 'Covered Policy';
    $coveredKey = BaselineSubjectKey::fromDisplayName($coveredDisplayName);
    expect($coveredKey)->not->toBeNull();

    $coveredWorkspaceId = BaselineSubjectKey::workspaceSafeSubjectExternalId(
        policyType: 'deviceConfiguration',
        subjectKey: (string) $coveredKey,
    );

    $baselineHash = app(BaselineSnapshotIdentity::class)->hashItemContent(
        policyType: 'deviceConfiguration',
        subjectExternalId: $coveredExternalId,
        metaJsonb: ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_BASELINE'],
    );

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => $coveredWorkspaceId,
        'subject_key' => (string) $coveredKey,
        'policy_type' => 'deviceConfiguration',
        'baseline_hash' => $baselineHash,
        'meta_jsonb' => [
            'display_name' => $coveredDisplayName,
            'evidence' => [
                'fidelity' => 'meta',
                'source' => 'inventory',
                'observed_at' => now()->toIso8601String(),
            ],
        ],
    ]);

    $uncoveredDisplayName = 'Uncovered Policy';
    $uncoveredKey = BaselineSubjectKey::fromDisplayName($uncoveredDisplayName);
    expect($uncoveredKey)->not->toBeNull();

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId('deviceCompliancePolicy', (string) $uncoveredKey),
        'subject_key' => (string) $uncoveredKey,
        'policy_type' => 'deviceCompliancePolicy',
        'baseline_hash' => hash('sha256', 'uncovered'),
        'meta_jsonb' => [
            'display_name' => $uncoveredDisplayName,
            'evidence' => [
                'fidelity' => 'meta',
                'source' => 'inventory',
                'observed_at' => now()->toIso8601String(),
            ],
        ],
    ]);

    $inventorySyncRun = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::InventorySync->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::PartiallySucceeded->value,
        'completed_at' => now(),
        'context' => [
            'inventory' => [
                'coverage' => [
                    'policy_types' => [
                        'deviceConfiguration' => ['status' => 'succeeded'],
                        'deviceCompliancePolicy' => ['status' => 'failed'],
                    ],
                    'foundation_types' => [],
                ],
            ],
        ],
    ]);

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => $coveredExternalId,
        'policy_type' => 'deviceConfiguration',
        'display_name' => $coveredDisplayName,
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    $opService = app(OperationRunService::class);
    $compareRun = $opService->ensureRunWithIdentity(
        tenant: $tenant,
        type: OperationRunType::BaselineCompare->value,
        identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
        context: [
            'baseline_profile_id' => (int) $profile->getKey(),
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'effective_scope' => [
                'policy_types' => ['deviceConfiguration', 'deviceCompliancePolicy'],
                'foundation_types' => [],
            ],
        ],
        initiator: $user,
    );

    (new CompareBaselineToTenantJob($compareRun))->handle(
        app(BaselineSnapshotIdentity::class),
        app(AuditLogger::class),
        $opService,
    );

    $compareRun->refresh();
    expect($compareRun->status)->toBe('completed');
    expect($compareRun->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);

    $findings = Finding::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('source', 'baseline.compare')
        ->get();

    expect($findings)->toHaveCount(1);
    expect((string) data_get($findings->first(), 'evidence_jsonb.change_type'))->toBe('different_version');

    $context = is_array($compareRun->context) ? $compareRun->context : [];
    expect(data_get($context, 'baseline_compare.coverage.uncovered_types'))->toContain('deviceCompliancePolicy');
});
