<?php

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\OperationRun;
use App\Services\Baselines\BaselineCompareService;
use App\Support\Baselines\Compare\CompareStrategyRegistry;
use App\Support\Baselines\BaselineProfileStatus;
use App\Support\Baselines\BaselineReasonCodes;
use App\Support\Baselines\Compare\IntuneCompareStrategy;
use App\Support\Governance\GovernanceSubjectTaxonomyRegistry;
use App\Support\OperationRunType;
use Illuminate\Support\Facades\Queue;
use Tests\Feature\Baselines\Support\FakeCompareStrategy;
use Tests\Feature\Baselines\Support\FakeGovernanceSubjectTaxonomyRegistry;

// --- T040: Compare precondition 422 tests ---

it('rejects compare when tenant has no baseline assignment', function () {
    Queue::fake();

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

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

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

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

it('rejects compare when assigned profile is in draft status', function () {
    Queue::fake();

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

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

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

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

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

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

it('rejects compare when assigned profile is archived [EC-001]', function () {
    Queue::fake();

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

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

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

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

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

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

it('rejects compare when profile has no consumable snapshot', function () {
    Queue::fake();

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

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

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

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

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

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

it('rejects compare when the latest attempted snapshot is still building and no complete snapshot exists', function () {
    Queue::fake();

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

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

    BaselineSnapshot::factory()->building()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

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

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

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

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

it('rejects explicit snapshot overrides when the snapshot is historically superseded', 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' => []],
    ]);

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

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

    $profile->update(['active_snapshot_id' => $currentSnapshot->getKey()]);

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

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

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

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

it('enqueues compare successfully when all preconditions are met', 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' => []],
    ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $snapshot->getKey()]);

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

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

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

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

    $context = is_array($run->context) ? $run->context : [];
    expect($context['baseline_profile_id'])->toBe((int) $profile->getKey());
    expect($context['baseline_snapshot_id'])->toBe((int) $snapshot->getKey());
    expect(data_get($context, 'progress.phase.key'))->toBe('preparing');
    expect(data_get($context, 'progress.phase.label'))->toBe('Preparing baseline comparison.');

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

it('rejects compare when canonical scope spans multiple compare strategy families', function (): void {
    Queue::fake();

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

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

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

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $snapshot->getKey()]);

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

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

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

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

it('rejects compare when canonical scope uses an inactive subject type', function (): void {
    Queue::fake();

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

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

    BaselineProfile::query()
        ->whereKey($profile->getKey())
        ->update([
            'scope_jsonb' => json_encode([
                'version' => 2,
                'entries' => [
                    [
                        'domain_key' => 'platform_foundation',
                        'subject_class' => 'configuration_resource',
                        'subject_type_keys' => ['intuneRoleAssignment'],
                        'filters' => [],
                    ],
                ],
            ], JSON_THROW_ON_ERROR),
        ]);

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $snapshot->getKey()]);

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

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

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

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

it('rejects compare when canonical scope has no compatible compare strategy', function (): void {
    Queue::fake();

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

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

    $profile = BaselineProfile::factory()->active()->create([
        'workspace_id' => $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' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $snapshot->getKey()]);

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

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

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

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

it('uses an explicit snapshot override instead of baseline_profiles.active_snapshot_id when provided', 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' => []],
    ]);

    $activeSnapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $overrideSnapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $activeSnapshot->getKey()]);

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

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

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

    /** @var OperationRun $run */
    $run = $result['run'];
    $context = is_array($run->context) ? $run->context : [];

    expect($context['baseline_snapshot_id'])->toBe((int) $overrideSnapshot->getKey());

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

// --- EC-004: Concurrent compare reuses active run ---

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

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

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

    $snapshot = BaselineSnapshot::factory()->create([
        'workspace_id' => $tenant->workspace_id,
        'baseline_profile_id' => $profile->getKey(),
    ]);

    $profile->update(['active_snapshot_id' => $snapshot->getKey()]);

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

    $service = app(BaselineCompareService::class);

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

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