<?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\Policy;
use App\Models\PolicyVersion;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;
use Carbon\CarbonImmutable;

it('Baseline compare ignores current content evidence when baseline is meta (prevents false drift)', function () {
    [$user, $tenant] = createUserWithTenant();

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

    $baselineCapturedAt = CarbonImmutable::parse('2026-03-01 00:00:00');

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

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

    $inventorySyncRun = createInventorySyncOperationRunWithCoverage(
        tenant: $tenant,
        statusByType: ['deviceConfiguration' => 'succeeded'],
    );

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_type' => 'deviceConfiguration',
        'external_id' => 'policy-meta',
        'platform' => 'windows',
        'display_name' => 'Policy Meta',
    ]);

    $inventory = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => (string) $policy->external_id,
        'policy_type' => (string) $policy->policy_type,
        'display_name' => (string) $policy->display_name,
        'meta_jsonb' => [
            'odata_type' => '#microsoft.graph.deviceConfiguration',
            'etag' => 'W/"meta-etag"',
            'scope_tag_ids' => [],
            'assignment_target_count' => 1,
        ],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    $baselineMetaHash = app(BaselineSnapshotIdentity::class)->hashItemContent(
        policyType: (string) $inventory->policy_type,
        subjectExternalId: (string) $inventory->external_id,
        metaJsonb: is_array($inventory->meta_jsonb) ? $inventory->meta_jsonb : [],
    );

    $subjectKey = BaselineSubjectKey::fromDisplayName((string) $policy->display_name);
    expect($subjectKey)->not->toBeNull();

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId(
            policyType: (string) $policy->policy_type,
            subjectKey: (string) $subjectKey,
        ),
        'subject_key' => (string) $subjectKey,
        'policy_type' => (string) $policy->policy_type,
        'baseline_hash' => $baselineMetaHash,
        'meta_jsonb' => [
            'display_name' => (string) $policy->display_name,
            'evidence' => [
                'fidelity' => 'meta',
                'source' => 'inventory',
                'observed_at' => $baselineCapturedAt->toIso8601String(),
                'observed_operation_run_id' => null,
            ],
        ],
    ]);

    PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => (string) $policy->policy_type,
        'platform' => (string) $policy->platform,
        'captured_at' => $baselineCapturedAt->addHour(),
        'snapshot' => [
            'settings' => [
                ['displayName' => 'SettingA', 'value' => 2],
            ],
        ],
    ]);

    $opService = app(OperationRunService::class);
    $run = $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'], 'foundation_types' => []],
        ],
        initiator: $user,
    );

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

    expect(Finding::query()->where('managed_environment_id', (int) $tenant->getKey())->count())->toBe(0);

    $run->refresh();
    $context = is_array($run->context) ? $run->context : [];

    expect(data_get($context, 'baseline_compare.fidelity'))->toBe('meta');
    expect(data_get($context, 'baseline_compare.coverage.resolved_meta'))->toBe(1);
    expect(data_get($context, 'baseline_compare.coverage.baseline_meta'))->toBe(1);
});

it('Baseline compare records a gap when baseline is content but current content evidence is too old', function () {
    [$user, $tenant] = createUserWithTenant();

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

    $baselineCapturedAt = CarbonImmutable::parse('2026-03-01 00:00:00');

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

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

    $inventorySyncRun = createInventorySyncOperationRunWithCoverage(
        tenant: $tenant,
        statusByType: ['deviceConfiguration' => 'succeeded'],
    );

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_type' => 'deviceConfiguration',
        'external_id' => 'policy-content',
        'platform' => 'windows',
        'display_name' => 'Policy Content',
    ]);

    $snapshotPayload = [
        'settings' => [
            ['displayName' => 'SettingB', 'value' => 1],
        ],
    ];

    $baselineContentHash = expectedPolicyVersionContentHash(
        snapshot: $snapshotPayload,
        policyType: 'deviceConfiguration',
        platform: 'windows',
    );

    $subjectKey = BaselineSubjectKey::fromDisplayName((string) $policy->display_name);
    expect($subjectKey)->not->toBeNull();

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId(
            policyType: (string) $policy->policy_type,
            subjectKey: (string) $subjectKey,
        ),
        'subject_key' => (string) $subjectKey,
        'policy_type' => (string) $policy->policy_type,
        'baseline_hash' => $baselineContentHash,
        'meta_jsonb' => [
            'display_name' => (string) $policy->display_name,
            'evidence' => [
                'fidelity' => 'content',
                'source' => 'policy_version',
                'observed_at' => $baselineCapturedAt->toIso8601String(),
                'observed_operation_run_id' => null,
            ],
        ],
    ]);

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => (string) $policy->external_id,
        'policy_type' => (string) $policy->policy_type,
        'display_name' => (string) $policy->display_name,
        'meta_jsonb' => [
            'odata_type' => '#microsoft.graph.deviceConfiguration',
            'etag' => 'W/"meta-etag-content"',
            'scope_tag_ids' => [],
            'assignment_target_count' => 1,
        ],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => (string) $policy->policy_type,
        'platform' => (string) $policy->platform,
        'captured_at' => $baselineCapturedAt->subHour(),
        'snapshot' => $snapshotPayload,
    ]);

    $opService = app(OperationRunService::class);
    $run = $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'], 'foundation_types' => []],
        ],
        initiator: $user,
    );

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

    expect(Finding::query()->where('managed_environment_id', (int) $tenant->getKey())->count())->toBe(0);

    $run->refresh();
    $context = is_array($run->context) ? $run->context : [];

    expect(data_get($context, 'baseline_compare.fidelity'))->toBe('meta');
    expect(data_get($context, 'baseline_compare.coverage.resolved_meta'))->toBe(0);
    expect(data_get($context, 'baseline_compare.coverage.baseline_content'))->toBe(1);
    expect(data_get($context, 'baseline_compare.evidence_gaps.missing_current'))->toBe(1);
});
