<?php

use App\Jobs\CompareBaselineToTenantJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\InventoryItem;
use App\Models\Policy;
use App\Services\Baselines\BaselineContentCapturePhase;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Intune\AuditLogger;
use App\Services\Intune\PolicyCaptureOrchestrator;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineCaptureMode;
use App\Support\Baselines\BaselineEvidenceResumeToken;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\Baselines\PolicyVersionCapturePurpose;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunType;
use Tests\Feature\Baselines\Support\AssertsStructuredBaselineGaps;

it('records a resume token when full-content compare cannot capture all subjects within budget', function (): void {
    config()->set('tenantpilot.baselines.full_content_capture.enabled', true);
    config()->set('tenantpilot.baselines.full_content_capture.max_items_per_run', 1);
    config()->set('tenantpilot.baselines.full_content_capture.max_concurrency', 1);
    config()->set('tenantpilot.baselines.full_content_capture.max_retries', 0);

    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'capture_mode' => BaselineCaptureMode::FullContent->value,
        'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], '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()]);

    $displayNames = ['Resume Token A', 'Resume Token B'];

    foreach ($displayNames as $displayName) {
        $subjectKey = BaselineSubjectKey::fromDisplayName($displayName);
        expect($subjectKey)->not->toBeNull();

        BaselineSnapshotItem::factory()->create([
            'baseline_snapshot_id' => (int) $snapshot->getKey(),
            'subject_type' => 'policy',
            'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId('deviceConfiguration', (string) $subjectKey),
            'subject_key' => (string) $subjectKey,
            'policy_type' => 'deviceConfiguration',
            'baseline_hash' => hash('sha256', 'baseline'),
            'meta_jsonb' => [
                'display_name' => $displayName,
                'evidence' => [
                    'fidelity' => 'content',
                    'source' => 'policy_version',
                    'observed_at' => now()->toIso8601String(),
                ],
            ],
        ]);
    }

    $policies = [];

    foreach ($displayNames as $i => $displayName) {
        $policies[] = Policy::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'policy_type' => 'deviceConfiguration',
            'external_id' => $i === 0 ? 'resume-token-a' : 'resume-token-b',
            'platform' => 'windows',
            'display_name' => $displayName,
        ]);
    }

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

    foreach ($policies as $policy) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'workspace_id' => (int) $tenant->workspace_id,
            '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' => fake()->uuid()],
            'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
            'last_seen_at' => now(),
        ]);
    }

    $fakeOrchestrator = new class extends PolicyCaptureOrchestrator
    {
        public function __construct() {}

        public function capture(
            Policy $policy,
            \App\Models\ManagedEnvironment $tenant,
            bool $includeAssignments = false,
            bool $includeScopeTags = false,
            ?string $createdBy = null,
            array $metadata = [],
            PolicyVersionCapturePurpose $capturePurpose = PolicyVersionCapturePurpose::Backup,
            ?int $operationRunId = null,
            ?int $baselineProfileId = null,
        ): array {
            $version = \App\Models\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' => now(),
                'snapshot' => ['settings' => [['key' => 'k', 'value' => 1]]],
                'assignments' => [],
                'scope_tags' => [],
                'capture_purpose' => $capturePurpose,
                'operation_run_id' => $operationRunId,
                'baseline_profile_id' => $baselineProfileId,
            ]);

            return [
                'version' => $version,
                'captured' => [
                    'payload' => $version->snapshot,
                    'assignments' => [],
                    'scope_tags' => [],
                ],
            ];
        }
    };

    $contentCapturePhase = new BaselineContentCapturePhase($fakeOrchestrator);

    $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' => []],
            'capture_mode' => BaselineCaptureMode::FullContent->value,
        ],
        initiator: $user,
    );

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

    $run->refresh();

    expect($run->outcome)->toBe(OperationRunOutcome::PartiallySucceeded->value);

    $context = is_array($run->context) ? $run->context : [];
    expect(data_get($context, 'progress.phase.key'))->toBe('finalizing');
    expect(data_get($context, 'progress.phase.label'))->toBe('Finalizing baseline comparison.');
    $token = $context['baseline_compare']['resume_token'] ?? null;
    expect($token)->toBeString();

    $state = BaselineEvidenceResumeToken::decode((string) $token);
    expect($state)->toBeArray();
    expect($state)->toHaveKey('offset');
    expect($state['offset'])->toBe(1);
});

it('stores capture-phase gap subjects for policy-record-missing evidence gaps', function (): void {
    config()->set('tenantpilot.baselines.full_content_capture.enabled', true);
    config()->set('tenantpilot.baselines.full_content_capture.max_items_per_run', 10);
    config()->set('tenantpilot.baselines.full_content_capture.max_concurrency', 1);
    config()->set('tenantpilot.baselines.full_content_capture.max_retries', 0);

    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'capture_mode' => BaselineCaptureMode::FullContent->value,
        'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], '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()]);

    $displayName = 'Missing Capture Policy';
    $subjectKey = BaselineSubjectKey::fromDisplayName($displayName);
    expect($subjectKey)->not->toBeNull();

    BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'policy',
        'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId('deviceConfiguration', (string) $subjectKey),
        'subject_key' => (string) $subjectKey,
        'policy_type' => 'deviceConfiguration',
        'baseline_hash' => hash('sha256', 'baseline-missing-capture-policy'),
        'meta_jsonb' => [
            'display_name' => $displayName,
            'evidence' => [
                'fidelity' => 'content',
                'source' => 'policy_version',
                'observed_at' => now()->toIso8601String(),
            ],
        ],
    ]);

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

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => 'missing-capture-policy',
        'policy_type' => 'deviceConfiguration',
        'display_name' => $displayName,
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => fake()->uuid()],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    $contentCapturePhase = new BaselineContentCapturePhase(new class extends PolicyCaptureOrchestrator
    {
        public function __construct() {}

        public function capture(
            Policy $policy,
            \App\Models\ManagedEnvironment $tenant,
            bool $includeAssignments = false,
            bool $includeScopeTags = false,
            ?string $createdBy = null,
            array $metadata = [],
            PolicyVersionCapturePurpose $capturePurpose = PolicyVersionCapturePurpose::Backup,
            ?int $operationRunId = null,
            ?int $baselineProfileId = null,
        ): array {
            throw new \RuntimeException('Should not be called for a missing policy capture case.');
        }
    });

    $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' => []],
            'capture_mode' => BaselineCaptureMode::FullContent->value,
        ],
        initiator: $user,
    );

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

    $run->refresh();

    expect(data_get($run->context, 'baseline_compare.evidence_gaps.by_reason.policy_record_missing'))->toBe(1);

    $subjects = data_get($run->context, 'baseline_compare.evidence_gaps.subjects');

    expect($subjects)->toBeArray();
    AssertsStructuredBaselineGaps::assertStructuredSubjects($subjects);

    $missingSubject = collect($subjects)->firstWhere('reason_code', 'policy_record_missing');

    expect($missingSubject)->toBeArray()
        ->and(data_get($missingSubject, 'policy_type'))->toBe('deviceConfiguration')
        ->and(data_get($missingSubject, 'subject_key'))->toBe('missing capture policy')
        ->and(data_get($missingSubject, 'subject_external_id'))->toBe('missing-capture-policy')
        ->and(data_get($missingSubject, 'resolution_outcome'))->toBe('policy_record_missing')
        ->and(data_get($missingSubject, 'operator_action_category'))->toBe('run_policy_sync_or_backup');
});
