<?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;
use Tests\Support\AssertsDriftEvidenceContract;

it('writes diff-compatible drift evidence for different_version drift findings', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $policyType = 'deviceConfiguration';
    $displayName = 'Policy Alpha';
    $subjectKey = BaselineSubjectKey::fromDisplayName($displayName);

    expect($subjectKey)->not->toBeNull();

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

    $baselineCapturedAt = CarbonImmutable::now()->subHours(2)->setMicrosecond(123456);
    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
        'captured_at' => $baselineCapturedAt->subSecond(),
    ]);
    $profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);

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

    $externalId = 'policy-alpha-uuid';
    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => $externalId,
        'policy_type' => $policyType,
        'platform' => 'windows10',
        'display_name' => $displayName,
    ]);

    $baselineVersion = PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => $policyType,
        'platform' => 'windows10',
        'version_number' => 1,
        'captured_at' => $baselineCapturedAt,
        'snapshot' => ['etag' => 'E_BASELINE'],
        'assignments' => [],
        'scope_tags' => ['ids' => ['0'], 'names' => ['Default']],
    ]);

    $currentVersion = PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => $policyType,
        'platform' => 'windows10',
        'version_number' => 2,
        'captured_at' => $baselineCapturedAt->addMinutes(10),
        'snapshot' => ['etag' => 'E_CURRENT'],
        'assignments' => [],
        'scope_tags' => ['ids' => ['0'], 'names' => ['Default']],
    ]);

    $baselineHash = expectedPolicyVersionContentHash(
        snapshot: is_array($baselineVersion->snapshot) ? $baselineVersion->snapshot : [],
        policyType: $policyType,
        platform: is_string($baselineVersion->platform) ? $baselineVersion->platform : null,
        assignments: is_array($baselineVersion->assignments) ? $baselineVersion->assignments : [],
        scopeTags: is_array($baselineVersion->scope_tags) ? $baselineVersion->scope_tags : [],
        secretFingerprints: is_array($baselineVersion->secret_fingerprints) ? $baselineVersion->secret_fingerprints : [],
        redactionVersion: is_numeric($baselineVersion->redaction_version) ? (int) $baselineVersion->redaction_version : null,
    );

    $workspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId($policyType, (string) $subjectKey);

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

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => $externalId,
        'policy_type' => $policyType,
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E_CURRENT_1'],
        'display_name' => $displayName,
        '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' => [$policyType], 'foundation_types' => []],
        ],
        initiator: $user,
    );

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

    $finding = Finding::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('source', 'baseline.compare')
        ->where('finding_type', Finding::FINDING_TYPE_DRIFT)
        ->sole();

    $evidence = is_array($finding->evidence_jsonb) ? $finding->evidence_jsonb : [];

    AssertsDriftEvidenceContract::assertValid($evidence);

    expect((string) ($evidence['change_type'] ?? ''))->toBe('different_version');
    expect(data_get($evidence, 'summary.kind'))->toBe('policy_snapshot');
    expect(data_get($evidence, 'baseline.policy_version_id'))->toBe((int) $baselineVersion->getKey());
    expect(data_get($evidence, 'current.policy_version_id'))->toBe((int) $currentVersion->getKey());
    expect(data_get($evidence, 'provenance.baseline_profile_id'))->toBe((int) $profile->getKey());
    expect(data_get($evidence, 'provenance.baseline_snapshot_id'))->toBe((int) $snapshot->getKey());
    expect(data_get($evidence, 'provenance.compare_operation_run_id'))->toBe((int) $compareRun->getKey());
    expect(data_get($evidence, 'provenance.inventory_sync_run_id'))->toBe((int) $inventorySyncRun->getKey());
});

it('writes diff-compatible drift evidence for missing_policy drift findings', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $policyType = 'deviceConfiguration';
    $displayName = 'Policy Alpha';
    $subjectKey = BaselineSubjectKey::fromDisplayName($displayName);

    expect($subjectKey)->not->toBeNull();

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

    $baselineCapturedAt = CarbonImmutable::now()->subHours(2)->setMicrosecond(123456);
    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
        'captured_at' => $baselineCapturedAt->subSecond(),
    ]);
    $profile->update(['active_snapshot_id' => (int) $snapshot->getKey()]);

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

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'policy-alpha-uuid',
        'policy_type' => $policyType,
        'platform' => 'windows10',
        'display_name' => $displayName,
    ]);

    $baselineVersion = PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => $policyType,
        'platform' => 'windows10',
        'version_number' => 1,
        'captured_at' => $baselineCapturedAt,
        'snapshot' => ['etag' => 'E_BASELINE'],
        'assignments' => [],
        'scope_tags' => ['ids' => ['0'], 'names' => ['Default']],
    ]);

    $baselineHash = expectedPolicyVersionContentHash(
        snapshot: is_array($baselineVersion->snapshot) ? $baselineVersion->snapshot : [],
        policyType: $policyType,
        platform: is_string($baselineVersion->platform) ? $baselineVersion->platform : null,
        assignments: is_array($baselineVersion->assignments) ? $baselineVersion->assignments : [],
        scopeTags: is_array($baselineVersion->scope_tags) ? $baselineVersion->scope_tags : [],
        secretFingerprints: is_array($baselineVersion->secret_fingerprints) ? $baselineVersion->secret_fingerprints : [],
        redactionVersion: is_numeric($baselineVersion->redaction_version) ? (int) $baselineVersion->redaction_version : null,
    );

    $workspaceSafeExternalId = BaselineSubjectKey::workspaceSafeSubjectExternalId($policyType, (string) $subjectKey);

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

    $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' => [$policyType], 'foundation_types' => []],
        ],
        initiator: $user,
    );

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

    $finding = Finding::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('source', 'baseline.compare')
        ->where('finding_type', Finding::FINDING_TYPE_DRIFT)
        ->sole();

    $evidence = is_array($finding->evidence_jsonb) ? $finding->evidence_jsonb : [];

    AssertsDriftEvidenceContract::assertValid($evidence);

    expect((string) ($evidence['change_type'] ?? ''))->toBe('missing_policy');
    expect(data_get($evidence, 'summary.kind'))->toBe('policy_snapshot');
    expect(data_get($evidence, 'baseline.policy_version_id'))->toBe((int) $baselineVersion->getKey());
    expect(data_get($evidence, 'current.policy_version_id'))->toBeNull();
    expect(data_get($evidence, 'provenance.baseline_profile_id'))->toBe((int) $profile->getKey());
    expect(data_get($evidence, 'provenance.baseline_snapshot_id'))->toBe((int) $snapshot->getKey());
    expect(data_get($evidence, 'provenance.compare_operation_run_id'))->toBe((int) $compareRun->getKey());
    expect(data_get($evidence, 'provenance.inventory_sync_run_id'))->toBe((int) $inventorySyncRun->getKey());
});
