<?php

declare(strict_types=1);

use App\Jobs\CaptureBaselineSnapshotJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\InventoryItem;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Baselines\InventoryMetaContract;
use App\Services\Intune\AuditLogger;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;

it('captures intune role definitions with identity metadata and excludes role assignments from the baseline snapshot', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

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

    $policy = Policy::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'external_id' => 'role-def-1',
        'display_name' => 'Security Reader',
        'policy_type' => 'intuneRoleDefinition',
        'platform' => 'all',
    ]);

    $version = PolicyVersion::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'policy_id' => (int) $policy->getKey(),
        'policy_type' => 'intuneRoleDefinition',
        'platform' => 'all',
        'captured_at' => now()->subMinute(),
        'snapshot' => [
            'displayName' => 'Security Reader',
            'description' => 'Security reporting role',
            'isBuiltIn' => false,
            'rolePermissions' => [
                [
                    'resourceActions' => [
                        [
                            'allowedResourceActions' => ['Microsoft.Intune/managedDevices/read'],
                        ],
                    ],
                ],
            ],
        ],
    ]);

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'external_id' => 'role-def-1',
        'policy_type' => 'intuneRoleDefinition',
        'display_name' => 'Security Reader',
        'category' => 'RBAC',
        'platform' => 'all',
        'meta_jsonb' => [
            'odata_type' => '#microsoft.graph.deviceAndAppManagementRoleDefinition',
            'etag' => 'E-RBAC-1',
            'is_built_in' => false,
            'role_permission_count' => 1,
            'warnings' => [],
        ],
        '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' => 'role-assignment-1',
        'policy_type' => 'intuneRoleAssignment',
        'display_name' => 'Security Reader Assignment',
        'category' => 'RBAC',
        'platform' => 'all',
        'meta_jsonb' => [
            'odata_type' => '#microsoft.graph.deviceAndAppManagementRoleAssignment',
            'etag' => 'E-RBAC-A1',
            'warnings' => [],
        ],
        'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
        'last_seen_at' => now(),
    ]);

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

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

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

    expect(BaselineSnapshotItem::query()->where('baseline_snapshot_id', (int) $snapshot->getKey())->count())->toBe(1);

    $item = BaselineSnapshotItem::query()
        ->where('baseline_snapshot_id', (int) $snapshot->getKey())
        ->sole();

    $expectedSubjectKey = BaselineSubjectKey::forPolicy('intuneRoleDefinition', 'Security Reader', 'role-def-1');
    $expectedExternalReference = BaselineSubjectKey::workspaceSafeSubjectExternalIdForPolicy('intuneRoleDefinition', 'Security Reader', 'role-def-1');

    expect($item->policy_type)->toBe('intuneRoleDefinition');
    expect($item->subject_key)->toBe($expectedSubjectKey);
    expect($item->subject_external_id)->toBe($expectedExternalReference);
    expect($item->subject_external_id)->not->toBe('role-def-1');

    $meta = is_array($item->meta_jsonb) ? $item->meta_jsonb : [];

    expect(data_get($meta, 'identity.strategy'))->toBe('external_id');
    expect(data_get($meta, 'rbac.is_built_in'))->toBeFalse();
    expect(data_get($meta, 'rbac.role_permission_count'))->toBe(1);
    expect(data_get($meta, 'version_reference.policy_version_id'))->toBe((int) $version->getKey());
    expect(data_get($meta, 'evidence.source'))->toBe('policy_version');
});
