<?php

use App\Models\Finding;
use App\Models\InventorySyncRun;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Services\Drift\DriftFindingGenerator;

test('it creates a drift finding when policy snapshot changes', function () {
    [, $tenant] = createUserWithTenant(role: 'manager');

    $scopeKey = hash('sha256', 'scope-policy-snapshot');

    $baseline = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'selection_payload' => ['policy_types' => ['deviceConfiguration']],
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDays(2),
    ]);

    $current = InventorySyncRun::factory()->for($tenant)->create([
        'selection_hash' => $scopeKey,
        'selection_payload' => ['policy_types' => ['deviceConfiguration']],
        'status' => InventorySyncRun::STATUS_SUCCESS,
        'finished_at' => now()->subDay(),
    ]);

    $policy = Policy::factory()->for($tenant)->create([
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows10',
    ]);

    PolicyVersion::factory()->for($tenant)->for($policy)->create([
        'version_number' => 1,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => $baseline->finished_at->copy()->subMinute(),
        'snapshot' => ['customSettingFoo' => 'Old value'],
        'assignments' => [],
    ]);

    PolicyVersion::factory()->for($tenant)->for($policy)->create([
        'version_number' => 2,
        'policy_type' => $policy->policy_type,
        'platform' => $policy->platform,
        'captured_at' => $current->finished_at->copy()->subMinute(),
        'snapshot' => ['customSettingFoo' => 'New value'],
        'assignments' => [],
    ]);

    $generator = app(DriftFindingGenerator::class);
    $created = $generator->generate($tenant, $baseline, $current, $scopeKey);

    expect($created)->toBe(1);

    $finding = Finding::query()
        ->where('tenant_id', $tenant->getKey())
        ->where('finding_type', Finding::FINDING_TYPE_DRIFT)
        ->where('scope_key', $scopeKey)
        ->where('subject_type', 'policy')
        ->first();

    expect($finding)->not->toBeNull();
    expect($finding->subject_external_id)->toBe($policy->external_id);
    expect($finding->evidence_jsonb)->toHaveKey('change_type', 'modified');
    expect($finding->evidence_jsonb)
        ->toHaveKey('summary.changed_fields')
        ->and($finding->evidence_jsonb['summary']['changed_fields'])->toContain('snapshot_hash')
        ->and($finding->evidence_jsonb)->toHaveKey('baseline.snapshot_hash')
        ->and($finding->evidence_jsonb)->toHaveKey('current.snapshot_hash')
        ->and($finding->evidence_jsonb)->not->toHaveKey('baseline.assignments_hash')
        ->and($finding->evidence_jsonb)->not->toHaveKey('current.assignments_hash');
});
