<?php

declare(strict_types=1);

use App\Jobs\CaptureBaselineSnapshotJob;
use App\Models\BaselineProfile;
use App\Models\InventoryItem;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\InventoryMetaContract;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineCaptureMode;
use App\Support\OperationRunType;
use Tests\Feature\Baselines\Support\AssertsStructuredBaselineGaps;

it('classifies structural foundation capture gaps separately from missing local policy records', function (): void {
    config()->set('tenantpilot.baselines.full_content_capture.enabled', true);
    config()->set('tenantpilot.baselines.full_content_capture.max_items_per_run', 50);
    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' => ['roleScopeTag'],
        ],
    ]);

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

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

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => 'scope-tag-1',
        'policy_type' => 'roleScopeTag',
        'display_name' => 'Structural Foundation Subject',
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.roleScopeTag', 'etag' => 'etag-scope-tag'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    $run = app(OperationRunService::class)->ensureRunWithIdentity(
        tenant: $tenant,
        type: OperationRunType::BaselineCapture->value,
        identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
        context: [
            'baseline_profile_id' => (int) $profile->getKey(),
            'source_environment_id' => (int) $tenant->getKey(),
            'effective_scope' => [
                'policy_types' => ['deviceConfiguration'],
                'foundation_types' => ['roleScopeTag'],
                'truthful_types' => ['deviceConfiguration', 'roleScopeTag'],
            ],
            'capture_mode' => BaselineCaptureMode::FullContent->value,
        ],
        initiator: $user,
    );

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

    $run->refresh();

    expect(data_get($run->context, 'baseline_capture.gaps.by_reason.policy_not_found'))->toBeNull()
        ->and(data_get($run->context, 'baseline_capture.gaps.by_reason.policy_record_missing'))->toBe(1)
        ->and(data_get($run->context, 'baseline_capture.gaps.by_reason.foundation_not_policy_backed'))->toBe(1);

    $subjects = data_get($run->context, 'baseline_capture.gaps.subjects');

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

    $subjectsByType = collect($subjects)->keyBy('policy_type');

    expect(data_get($subjectsByType['deviceConfiguration'], 'subject_class'))->toBe('policy_backed')
        ->and(data_get($subjectsByType['deviceConfiguration'], 'resolution_outcome'))->toBe('policy_record_missing')
        ->and(data_get($subjectsByType['deviceConfiguration'], 'reason_code'))->toBe('policy_record_missing')
        ->and(data_get($subjectsByType['deviceConfiguration'], 'structural'))->toBeFalse();

    expect(data_get($subjectsByType['roleScopeTag'], 'subject_class'))->toBe('foundation_backed')
        ->and(data_get($subjectsByType['roleScopeTag'], 'resolution_outcome'))->toBe('foundation_inventory_only')
        ->and(data_get($subjectsByType['roleScopeTag'], 'reason_code'))->toBe('foundation_not_policy_backed')
        ->and(data_get($subjectsByType['roleScopeTag'], 'structural'))->toBeTrue();
});
