<?php

declare(strict_types=1);

require_once __DIR__.'/Support/FakeCompareStrategy.php';

use App\Jobs\CompareBaselineToTenantJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineTenantAssignment;
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Services\Baselines\BaselineCompareService;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\Compare\CompareStrategyRegistry;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OperationRunType;
use App\Support\Governance\GovernanceSubjectTaxonomyRegistry;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\Feature\Baselines\Support\FakeCompareStrategy;
use Tests\Feature\Baselines\Support\FakeGovernanceSubjectTaxonomyRegistry;

uses(RefreshDatabase::class);

it('runs a future-domain compare strategy through the shared lifecycle without implicit intune fallback', function (): void {
    Queue::fake();

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

    app()->instance(GovernanceSubjectTaxonomyRegistry::class, new FakeGovernanceSubjectTaxonomyRegistry);
    app()->instance(CompareStrategyRegistry::class, new CompareStrategyRegistry([
        app(FakeCompareStrategy::class),
    ]));

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'scope_jsonb' => [
            'version' => 2,
            'entries' => [[
                'domain_key' => 'entra',
                'subject_class' => 'control',
                'subject_type_keys' => ['conditionalAccessPolicy'],
                'filters' => [],
            ]],
        ],
    ]);

    $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()]);

    BaselineTenantAssignment::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'baseline_profile_id' => (int) $profile->getKey(),
    ]);

    $displayName = 'Conditional Access Global Block';
    $externalId = 'conditional-access-policy-1';
    $subjectKey = app(BaselineSnapshotIdentity::class)->subjectKey(
        policyType: 'conditionalAccessPolicy',
        displayName: $displayName,
        subjectExternalId: $externalId,
    ) ?? $externalId;

    $baselineMeta = [
        'display_name' => $displayName,
        'conditions' => ['users' => ['includeGuestsOrExternalUsers' => true]],
    ];
    $currentMeta = [
        'display_name' => $displayName,
        'conditions' => ['users' => ['includeGuestsOrExternalUsers' => false]],
    ];

    $baselineHash = app(BaselineSnapshotIdentity::class)->hashItemContent(
        policyType: 'conditionalAccessPolicy',
        subjectExternalId: $externalId,
        metaJsonb: $baselineMeta,
    );

    \App\Models\BaselineSnapshotItem::factory()->create([
        'baseline_snapshot_id' => (int) $snapshot->getKey(),
        'subject_type' => 'control',
        'subject_external_id' => $externalId,
        'subject_key' => $subjectKey,
        'policy_type' => 'conditionalAccessPolicy',
        'baseline_hash' => $baselineHash,
        'meta_jsonb' => $baselineMeta,
    ]);

    $inventorySyncRun = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => OperationRunType::InventorySync->value,
        'status' => OperationRunStatus::Completed->value,
        'outcome' => OperationRunOutcome::Succeeded->value,
        'completed_at' => now(),
        'context' => [
            'inventory' => [
                'coverage' => [
                    'policy_types' => [
                        'conditionalAccessPolicy' => ['status' => 'succeeded'],
                    ],
                    'foundation_types' => [],
                ],
            ],
        ],
    ]);

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => $externalId,
        'policy_type' => 'conditionalAccessPolicy',
        'display_name' => $displayName,
        'meta_jsonb' => $currentMeta,
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

    $service = app(BaselineCompareService::class);
    $result = $service->startCompare($tenant, $user);

    expect($result['ok'] ?? false)->toBeTrue();
    Queue::assertPushed(CompareBaselineToTenantJob::class);

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

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

    $run->refresh();

    expect($run->status)->toBe(OperationRunStatus::Completed->value)
        ->and($run->outcome)->toBe(OperationRunOutcome::Succeeded->value)
        ->and(data_get($run->context, 'baseline_compare.strategy.key'))->toBe('future_control')
        ->and(data_get($run->context, 'baseline_compare.strategy.selection_state'))->toBe('supported')
        ->and(data_get($run->context, 'findings.counts_by_change_type.different_version'))->toBe(1)
        ->and(data_get($run->context, 'result.findings_total'))->toBe(1);

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

    expect($finding)->not->toBeNull()
        ->and($finding?->subject_type)->toBe('control')
        ->and(data_get($finding?->evidence_jsonb, 'summary.kind'))->toBe('control_snapshot')
        ->and(data_get($finding?->evidence_jsonb, 'policy_type'))->toBe('conditionalAccessPolicy');
});