<?php

use App\Jobs\CaptureBaselineSnapshotJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Services\Baselines\BaselineCaptureService;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\InventoryMetaContract;
use App\Services\Drift\DriftHasher;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineProfileStatus;
use App\Support\Baselines\BaselineReasonCodes;
use App\Support\Baselines\BaselineSnapshotLifecycleState;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;
use Illuminate\Support\Facades\Queue;

function createBaselineCaptureInventoryBasis(
    ManagedEnvironment $tenant,
    array $statusByType,
    array $attributes = [],
): OperationRun {
    return createInventorySyncOperationRunWithCoverage($tenant, $statusByType, [], $attributes);
}

function runBaselineCaptureJob(
    OperationRun $run,
    ?OperationRunService $operationRunService = null,
): void {
    $operationRunService ??= app(OperationRunService::class);

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

// --- T031: Capture enqueue + precondition tests ---

it('enqueues capture for an active profile and creates an operation run', function () {
    Queue::fake();

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

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

    /** @var BaselineCaptureService $service */
    $service = app(BaselineCaptureService::class);
    $result = $service->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeTrue();
    expect($result)->toHaveKey('run');

    /** @var OperationRun $run */
    $run = $result['run'];
    expect($run->type)->toBe(OperationRunType::BaselineCapture->value);
    expect($run->status)->toBe('queued');
    expect($run->managed_environment_id)->toBe((int) $tenant->getKey());

    $context = is_array($run->context) ? $run->context : [];
    expect($context['baseline_profile_id'])->toBe((int) $profile->getKey());
    expect($context['source_environment_id'])->toBe((int) $tenant->getKey());
    expect($context)->toHaveKey('effective_scope');
    expect(data_get($context, 'progress.phase.key'))->toBe('preparing');
    expect(data_get($context, 'progress.phase.label'))->toBe('Preparing baseline capture.');

    $effectiveScope = is_array($context['effective_scope'] ?? null) ? $context['effective_scope'] : [];
    expect($effectiveScope['policy_types'])->toBe(['deviceConfiguration']);
    expect($effectiveScope['foundation_types'])->toBe([]);
    expect($effectiveScope['all_types'])->toBe(['deviceConfiguration']);
    expect($effectiveScope['foundations_included'])->toBeFalse();
    expect(data_get($context, 'baseline_capture.inventory_sync_run_id'))->toBe((int) $inventorySyncRun->getKey());
    expect(data_get($context, 'baseline_capture.eligibility.phase'))->toBe('preflight');
    expect(data_get($context, 'baseline_capture.eligibility.ok'))->toBeTrue();
    expect(data_get($context, 'baseline_capture.eligibility.covered_types'))->toBe(['deviceConfiguration']);
    expect(data_get($context, 'baseline_capture.eligibility.uncovered_types'))->toBe([]);

    Queue::assertPushed(CaptureBaselineSnapshotJob::class);
});

it('rejects capture when no current inventory sync exists', function () {
    Queue::fake();

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

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

    $result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe(BaselineReasonCodes::CAPTURE_INVENTORY_MISSING);

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture when the latest inventory sync was blocked', function () {
    Queue::fake();

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

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

    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'succeeded',
    ], [
        'completed_at' => now()->subMinute(),
    ]);
    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'failed',
    ], [
        'outcome' => 'blocked',
        'completed_at' => now(),
    ]);

    $result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe(BaselineReasonCodes::CAPTURE_INVENTORY_BLOCKED);

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture when the latest inventory sync failed without falling back to an older success', function () {
    Queue::fake();

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

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

    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'succeeded',
    ], [
        'completed_at' => now()->subMinute(),
    ]);
    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'failed',
    ], [
        'outcome' => 'failed',
        'completed_at' => now(),
    ]);

    $result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe(BaselineReasonCodes::CAPTURE_INVENTORY_FAILED);

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture when the latest inventory coverage is unusable for the baseline scope', function () {
    Queue::fake();

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

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

    createBaselineCaptureInventoryBasis($tenant, [
        'deviceCompliancePolicy' => 'succeeded',
    ]);

    $result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe(BaselineReasonCodes::CAPTURE_UNUSABLE_COVERAGE);

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture for a draft profile with reason code', function () {
    Queue::fake();

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

    $profile = BaselineProfile::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'status' => BaselineProfileStatus::Draft->value,
    ]);

    $service = app(BaselineCaptureService::class);
    $result = $service->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe('baseline.capture.profile_not_active');

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture for an archived profile with reason code', function () {
    Queue::fake();

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

    $profile = BaselineProfile::factory()->archived()->create([
        'workspace_id' => $tenant->workspace_id,
    ]);

    $service = app(BaselineCaptureService::class);
    $result = $service->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe('baseline.capture.profile_not_active');

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(0);
});

it('rejects capture for a tenant from a different workspace', function () {
    Queue::fake();

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

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

    $service = app(BaselineCaptureService::class);
    $result = $service->startCapture($profile, $otherTenant, $user);

    expect($result['ok'])->toBeFalse();
    expect($result['reason_code'])->toBe('baseline.capture.missing_source_tenant');

    Queue::assertNotPushed(CaptureBaselineSnapshotJob::class);
});

// --- T032: Concurrent capture reuses active run [EC-004] ---

it('reuses an existing active run for the same profile/tenant instead of creating a new one', function () {
    Queue::fake();

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

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

    $service = app(BaselineCaptureService::class);

    $result1 = $service->startCapture($profile, $tenant, $user);
    $result2 = $service->startCapture($profile, $tenant, $user);

    expect($result1['ok'])->toBeTrue();
    expect($result2['ok'])->toBeTrue();

    expect($result1['run']->getKey())->toBe($result2['run']->getKey());
    expect(OperationRun::query()->where('type', OperationRunType::BaselineCapture->value)->count())->toBe(1);
});

// --- Snapshot dedupe + capture job execution ---

it('creates a snapshot with items when the capture job executes', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $inventoryA = InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'external_id' => 'policy-a',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy A',
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E1'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);
    $inventoryB = InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'external_id' => 'policy-b',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy B',
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E2'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);
    $inventoryC = InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'external_id' => 'policy-c',
        'policy_type' => 'deviceConfiguration',
        'display_name' => 'Policy C',
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'etag' => 'E3'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);

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

    runBaselineCaptureJob($run, $opService);

    $run->refresh();
    expect($run->status)->toBe('completed');
    expect($run->outcome)->toBe('succeeded');

    $counts = is_array($run->summary_counts) ? $run->summary_counts : [];
    expect((int) ($counts['total'] ?? 0))->toBe(3);
    expect((int) ($counts['succeeded'] ?? 0))->toBe(3);
    expect(data_get($run->context, 'progress.phase.key'))->toBe('finalizing');
    expect(data_get($run->context, 'progress.phase.label'))->toBe('Finalizing baseline capture.');

    $snapshot = BaselineSnapshot::query()
        ->where('baseline_profile_id', $profile->getKey())
        ->first();

    expect($snapshot)->not->toBeNull();
    expect($snapshot?->lifecycleState())->toBe(BaselineSnapshotLifecycleState::Complete);
    expect($snapshot?->completed_at)->not->toBeNull();
    expect($snapshot?->failed_at)->toBeNull();
    expect(data_get($snapshot?->completion_meta_jsonb ?? [], 'expected_items'))->toBe(3);
    expect(data_get($snapshot?->completion_meta_jsonb ?? [], 'persisted_items'))->toBe(3);
    expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(3);

    $builder = app(InventoryMetaContract::class);
    $hasher = app(DriftHasher::class);

    $items = BaselineSnapshotItem::query()
        ->where('baseline_snapshot_id', $snapshot->getKey())
        ->orderBy('subject_external_id')
        ->get();

    $subjectKeyA = BaselineSubjectKey::fromDisplayName((string) $inventoryA->display_name);
    $subjectKeyB = BaselineSubjectKey::fromDisplayName((string) $inventoryB->display_name);
    $subjectKeyC = BaselineSubjectKey::fromDisplayName((string) $inventoryC->display_name);

    expect($subjectKeyA)->not->toBeNull();
    expect($subjectKeyB)->not->toBeNull();
    expect($subjectKeyC)->not->toBeNull();

    $expectedSubjectExternalIds = [
        BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryA->policy_type, (string) $subjectKeyA),
        BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryB->policy_type, (string) $subjectKeyB),
        BaselineSubjectKey::workspaceSafeSubjectExternalId((string) $inventoryC->policy_type, (string) $subjectKeyC),
    ];
    sort($expectedSubjectExternalIds, SORT_STRING);

    expect($items->pluck('subject_external_id')->all())->toBe($expectedSubjectExternalIds);

    $inventoryBySubjectKey = [
        (string) $subjectKeyA => $inventoryA,
        (string) $subjectKeyB => $inventoryB,
        (string) $subjectKeyC => $inventoryC,
    ];

    foreach ($items as $item) {
        /** @var BaselineSnapshotItem $item */
        $inventory = $inventoryBySubjectKey[(string) $item->subject_key] ?? null;

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

        $contractSubjectExternalId = (string) ($inventory->external_id ?? '');

        $contract = $builder->build(
            policyType: (string) $inventory->policy_type,
            subjectExternalId: $contractSubjectExternalId,
            metaJsonb: is_array($inventory->meta_jsonb) ? $inventory->meta_jsonb : [],
        );

        expect($item->baseline_hash)->toBe($hasher->hashNormalized($contract));

        $meta = is_array($item->meta_jsonb) ? $item->meta_jsonb : [];
        expect(data_get($meta, 'display_name'))->toBe((string) ($inventory->display_name ?? ''));
        expect(data_get($meta, 'evidence.fidelity'))->toBe('meta');
        expect(data_get($meta, 'evidence.source'))->toBe('inventory');
        expect(data_get($meta, 'meta_contract'))->toBeNull();
    }

    expect(data_get($run->context, 'baseline_capture.inventory_sync_run_id'))->toBe((int) $inventorySyncRun->getKey());
    expect(data_get($run->context, 'baseline_capture.eligibility.phase'))->toBe('runtime_recheck');
    expect(data_get($run->context, 'baseline_capture.eligibility.ok'))->toBeTrue();
    expect(data_get($run->context, 'baseline_capture.eligibility.changed_after_enqueue'))->toBeFalse();
    expect(data_get($run->context, 'baseline_capture.current_baseline_changed'))->toBeTrue();
    expect(data_get($run->context, 'baseline_capture.previous_current_snapshot_exists'))->toBeFalse();
    expect(data_get($run->context, 'result.current_baseline_changed'))->toBeTrue();

    $profile->refresh();
    expect($profile->active_snapshot_id)->toBe((int) $snapshot->getKey());
});

it('preserves the previous complete snapshot when a newer snapshot is incomplete', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $previousSnapshot = BaselineSnapshot::factory()->complete()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
        'captured_at' => now()->subDay(),
        'completed_at' => now()->subDay(),
    ]);

    $newSnapshot = BaselineSnapshot::factory()->incomplete(BaselineReasonCodes::SNAPSHOT_CAPTURE_FAILED)->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
        'captured_at' => now(),
    ]);

    $profile->update(['active_snapshot_id' => (int) $previousSnapshot->getKey()]);
    $profile->refresh();

    expect($newSnapshot->lifecycleState())->toBe(BaselineSnapshotLifecycleState::Incomplete)
        ->and(data_get($newSnapshot->completion_meta_jsonb, 'finalization_reason_code'))->toBe(BaselineReasonCodes::SNAPSHOT_CAPTURE_FAILED);

    expect($profile->resolveCurrentConsumableSnapshot()?->is($previousSnapshot))->toBeTrue()
        ->and($profile->resolveLatestAttemptedSnapshot()?->is($newSnapshot))->toBeTrue()
        ->and($profile->active_snapshot_id)->toBe((int) $previousSnapshot->getKey());
});

it('dedupes snapshots when content is unchanged', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    InventoryItem::factory()->count(2)->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'policy_type' => 'deviceConfiguration',
        'meta_jsonb' => ['odata_type' => '#microsoft.graph.deviceConfiguration', 'stable_field' => 'value'],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);

    $opService = app(OperationRunService::class);
    $idService = app(BaselineSnapshotIdentity::class);
    $metaContract = app(InventoryMetaContract::class);
    $auditLogger = app(AuditLogger::class);

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

    (new CaptureBaselineSnapshotJob($run1))->handle($idService, $metaContract, $auditLogger, $opService);

    $snapshotCountAfterFirst = BaselineSnapshot::query()
        ->where('baseline_profile_id', $profile->getKey())
        ->count();

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

    $run2 = OperationRun::create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'user_id' => (int) $user->getKey(),
        'initiator_name' => $user->name,
        'type' => OperationRunType::BaselineCapture->value,
        'status' => 'queued',
        'outcome' => 'pending',
        'run_identity_hash' => hash('sha256', 'second-run-'.now()->timestamp),
        'context' => [
            'baseline_profile_id' => (int) $profile->getKey(),
            'source_environment_id' => (int) $tenant->getKey(),
            'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
        ],
    ]);

    (new CaptureBaselineSnapshotJob($run2))->handle($idService, $metaContract, $auditLogger, $opService);

    $snapshotCountAfterSecond = BaselineSnapshot::query()
        ->where('baseline_profile_id', $profile->getKey())
        ->count();

    expect($snapshotCountAfterSecond)->toBe(1);
});

it('blocks a queued capture when the latest inventory basis fails after enqueue and keeps the prior current baseline', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $previousSnapshot = BaselineSnapshot::factory()->complete()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);
    $profile->update(['active_snapshot_id' => (int) $previousSnapshot->getKey()]);

    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'succeeded',
    ], [
        'completed_at' => now()->subMinute(),
    ]);

    Queue::fake();

    $result = app(BaselineCaptureService::class)->startCapture($profile, $tenant, $user);

    expect($result['ok'])->toBeTrue();

    createBaselineCaptureInventoryBasis($tenant, [
        'deviceConfiguration' => 'failed',
    ], [
        'outcome' => 'failed',
        'completed_at' => now(),
    ]);

    /** @var OperationRun $run */
    $run = $result['run'];
    runBaselineCaptureJob($run);

    $run->refresh();
    $profile->refresh();

    expect($run->status)->toBe('completed');
    expect($run->outcome)->toBe('blocked');
    expect($profile->active_snapshot_id)->toBe((int) $previousSnapshot->getKey());
    expect(data_get($run->context, 'reason_code'))->toBe(BaselineReasonCodes::CAPTURE_INVENTORY_FAILED);
    expect(data_get($run->context, 'baseline_capture.reason_code'))->toBe(BaselineReasonCodes::CAPTURE_INVENTORY_FAILED);
    expect(data_get($run->context, 'baseline_capture.current_baseline_changed'))->toBeFalse();
    expect(data_get($run->context, 'baseline_capture.previous_current_snapshot_exists'))->toBeTrue();
    expect(data_get($run->context, 'baseline_capture.eligibility.changed_after_enqueue'))->toBeTrue();
    expect(data_get($run->context, 'result.current_baseline_changed'))->toBeFalse();
});

// --- EC-005: Zero-subject captures stay visible but non-authoritative ---

it('records a zero-subject capture as partially succeeded with a non-consumable snapshot', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

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

    runBaselineCaptureJob($run, $opService);

    $run->refresh();
    expect($run->status)->toBe('completed');
    expect($run->outcome)->toBe('partially_succeeded');
    expect(data_get($run->context, 'reason_code'))->toBe(BaselineReasonCodes::CAPTURE_ZERO_SUBJECTS);
    expect(data_get($run->context, 'baseline_capture.reason_code'))->toBe(BaselineReasonCodes::CAPTURE_ZERO_SUBJECTS);
    expect(data_get($run->context, 'baseline_capture.subjects_total'))->toBe(0);
    expect(data_get($run->context, 'baseline_capture.current_baseline_changed'))->toBeFalse();
    expect(data_get($run->context, 'result.current_baseline_changed'))->toBeFalse();
    expect(data_get($run->context, 'result.snapshot_lifecycle'))->toBe(BaselineSnapshotLifecycleState::Incomplete->value);

    $counts = is_array($run->summary_counts) ? $run->summary_counts : [];
    expect((int) ($counts['total'] ?? 0))->toBe(0);
    expect((int) ($counts['failed'] ?? 0))->toBe(0);

    $snapshot = BaselineSnapshot::query()
        ->where('baseline_profile_id', $profile->getKey())
        ->first();

    expect($snapshot)->not->toBeNull();
    expect($snapshot?->lifecycleState())->toBe(BaselineSnapshotLifecycleState::Incomplete);
    expect(data_get($snapshot?->completion_meta_jsonb ?? [], 'finalization_reason_code'))->toBe(BaselineReasonCodes::CAPTURE_ZERO_SUBJECTS);
    expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(0);

    $profile->refresh();
    expect($profile->active_snapshot_id)->toBeNull();
});

it('captures all inventory items when scope has empty policy_types (all types)', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'policy_type' => 'deviceConfiguration',
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);

    InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'policy_type' => 'deviceCompliancePolicy',
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);

    // Foundation types are excluded by default (unless foundation_types is selected).
    InventoryItem::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'workspace_id' => $tenant->workspace_id,
        'policy_type' => 'assignmentFilter',
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
    ]);

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

    runBaselineCaptureJob($run, $opService);

    $run->refresh();
    expect($run->status)->toBe('completed');

    $counts = is_array($run->summary_counts) ? $run->summary_counts : [];
    expect((int) ($counts['total'] ?? 0))->toBe(2);

    $snapshot = BaselineSnapshot::query()
        ->where('baseline_profile_id', $profile->getKey())
        ->first();

    expect($snapshot)->not->toBeNull();
    expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', $snapshot->getKey())->count())->toBe(2);
});
