<?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\Drift\DriftHasher;
use App\Services\Drift\Normalizers\AssignmentsNormalizer;
use App\Services\Drift\Normalizers\ScopeTagsNormalizer;
use App\Services\Drift\Normalizers\SettingsNormalizer;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;
use Carbon\CarbonImmutable;

it('does not create drift for unchanged compliance actions when the baseline snapshot hash used the legacy signal', function (): void {
    [$tenant, $run] = createComplianceActionCompareFixture(
        baselineSnapshotPayload: [
            '@odata.type' => '#microsoft.graph.windows10CompliancePolicy',
            'bitLockerEnabled' => true,
            'scheduledActionsForRule' => [
                [
                    'ruleName' => null,
                    'scheduledActionConfigurations' => [
                        [
                            'id' => 'baseline-block',
                            'actionType' => 'block',
                            'gracePeriodHours' => 0,
                            'notificationTemplateId' => '00000000-0000-0000-0000-000000000000',
                        ],
                        [
                            'id' => 'baseline-retire',
                            'actionType' => 'retire',
                            'gracePeriodHours' => 2664,
                            'notificationTemplateId' => '6a204cbf-1acc-434d-83f9-486af129941f',
                        ],
                    ],
                ],
            ],
        ],
        currentSnapshotPayload: [
            '@odata.type' => '#microsoft.graph.windows10CompliancePolicy',
            'bitLockerEnabled' => true,
            'scheduledActionsForRule' => [
                [
                    'ruleName' => null,
                    'scheduledActionConfigurations' => [
                        [
                            'id' => 'current-block',
                            'actionType' => 'block',
                            'gracePeriodHours' => 0,
                            'notificationTemplateId' => '00000000-0000-0000-0000-000000000000',
                        ],
                        [
                            'id' => 'current-retire',
                            'actionType' => 'retire',
                            'gracePeriodHours' => 2664,
                            'notificationTemplateId' => '6a204cbf-1acc-434d-83f9-486af129941f',
                        ],
                    ],
                ],
            ],
        ],
    );

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

    $run->refresh();

    expect($run->status)->toBe('completed');
    expect(data_get($run->context, 'baseline_compare.reason_code'))->toBe('no_drift_detected');
    expect(Finding::query()->where('managed_environment_id', (int) $tenant->getKey())->count())->toBe(0);
});

it('creates drift when compliance noncompliance action timing changes', function (): void {
    [$tenant, $run] = createComplianceActionCompareFixture(
        baselineSnapshotPayload: [
            '@odata.type' => '#microsoft.graph.windows10CompliancePolicy',
            'bitLockerEnabled' => true,
            'scheduledActionsForRule' => [
                [
                    'ruleName' => null,
                    'scheduledActionConfigurations' => [
                        [
                            'id' => 'baseline-block',
                            'actionType' => 'block',
                            'gracePeriodHours' => 0,
                            'notificationTemplateId' => '00000000-0000-0000-0000-000000000000',
                        ],
                        [
                            'id' => 'baseline-retire',
                            'actionType' => 'retire',
                            'gracePeriodHours' => 2664,
                            'notificationTemplateId' => '6a204cbf-1acc-434d-83f9-486af129941f',
                        ],
                    ],
                ],
            ],
        ],
        currentSnapshotPayload: [
            '@odata.type' => '#microsoft.graph.windows10CompliancePolicy',
            'bitLockerEnabled' => true,
            'scheduledActionsForRule' => [
                [
                    'ruleName' => null,
                    'scheduledActionConfigurations' => [
                        [
                            'id' => 'current-block',
                            'actionType' => 'block',
                            'gracePeriodHours' => 264,
                            'notificationTemplateId' => '00000000-0000-0000-0000-000000000000',
                        ],
                        [
                            'id' => 'current-retire',
                            'actionType' => 'retire',
                            'gracePeriodHours' => 2664,
                            'notificationTemplateId' => '6a204cbf-1acc-434d-83f9-486af129941f',
                        ],
                    ],
                ],
            ],
        ],
    );

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

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

    expect($finding)->toBeInstanceOf(Finding::class);
    expect(data_get($finding, 'evidence_jsonb.change_type'))->toBe('different_version');
    expect(data_get($finding, 'evidence_jsonb.summary.kind'))->toBe('policy_snapshot');
    expect(data_get($finding, 'evidence_jsonb.baseline.policy_version_id'))->toBeInt();
    expect(data_get($finding, 'evidence_jsonb.current.policy_version_id'))->toBeInt();
});

function createComplianceActionCompareFixture(array $baselineSnapshotPayload, array $currentSnapshotPayload): array
{
    [$user, $tenant] = createUserWithTenant();

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

    $baselineCapturedAt = CarbonImmutable::parse('2026-03-06 00:18:39');

    $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: ['deviceCompliancePolicy' => 'succeeded'],
    );

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_type' => 'deviceCompliancePolicy',
        'external_id' => 'bitlocker-require-policy',
        'platform' => 'windows',
        'display_name' => 'Bitlocker Require',
    ]);

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

    PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'version_number' => 1,
        'policy_type' => (string) $policy->policy_type,
        'platform' => (string) $policy->platform,
        'captured_at' => $baselineCapturedAt,
        'snapshot' => $baselineSnapshotPayload,
        'assignments' => [],
        'scope_tags' => [],
    ]);

    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' => legacyComplianceSnapshotHash($baselineSnapshotPayload),
        '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.windows10CompliancePolicy',
            'etag' => 'W/"same-etag"',
            'scope_tag_ids' => [],
            'assignment_target_count' => 0,
        ],
        '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(),
        'version_number' => 2,
        'policy_type' => (string) $policy->policy_type,
        'platform' => (string) $policy->platform,
        'captured_at' => $baselineCapturedAt->addHour(),
        'snapshot' => $currentSnapshotPayload,
        'assignments' => [],
        'scope_tags' => [],
    ]);

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

    return [$tenant, $run];
}

function legacyComplianceSnapshotHash(array $snapshot): string
{
    $snapshotWithoutScheduledActions = $snapshot;
    unset($snapshotWithoutScheduledActions['scheduledActionsForRule'], $snapshotWithoutScheduledActions['scheduledActionsForRule@odata.context']);

    $settings = app(SettingsNormalizer::class)->normalizeForDiff(
        snapshot: $snapshotWithoutScheduledActions,
        policyType: 'deviceCompliancePolicy',
        platform: 'windows',
    );

    $templateIds = [];
    $scheduledActions = $snapshot['scheduledActionsForRule'] ?? null;

    if (is_array($scheduledActions)) {
        foreach ($scheduledActions as $rule) {
            if (! is_array($rule)) {
                continue;
            }

            $configs = $rule['scheduledActionConfigurations'] ?? null;

            if (! is_array($configs)) {
                continue;
            }

            foreach ($configs as $config) {
                if (! is_array($config) || ($config['actionType'] ?? null) !== 'notification') {
                    continue;
                }

                $templateId = $config['notificationTemplateId'] ?? $config['notificationMessageTemplateId'] ?? null;
                $templateId = is_string($templateId) ? trim($templateId) : null;

                if ($templateId === null || $templateId === '' || strtolower($templateId) === '00000000-0000-0000-0000-000000000000') {
                    continue;
                }

                $templateIds[] = $templateId;
            }
        }
    }

    $templateIds = array_values(array_unique($templateIds));
    sort($templateIds);

    if ($templateIds !== []) {
        $settings['Compliance notifications > Template IDs'] = $templateIds;
    }

    return app(DriftHasher::class)->hashNormalized([
        'settings' => $settings,
        'assignments' => app(AssignmentsNormalizer::class)->normalizeForDiff([]),
        'scope_tag_ids' => app(ScopeTagsNormalizer::class)->normalizeIds([]),
    ]);
}
