<?php

declare(strict_types=1);

use App\Models\ManagedEnvironment;
use App\Support\Links\RequiredPermissionsLinks;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Verification\ManagedEnvironmentPermissionCheckClusters;
use App\Support\Verification\VerificationCheckStatus;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('surfaces a dedicated RBAC permission reason when DeviceManagementRBAC.Read.All is missing', function (): void {
    $tenant = ManagedEnvironment::factory()->create(['external_id' => 'tenant-rbac-check']);

    $checks = ManagedEnvironmentPermissionCheckClusters::buildChecks($tenant, [
        [
            'key' => 'DeviceManagementRBAC.Read.All',
            'type' => 'application',
            'description' => 'Read Intune RBAC roles and assignments',
            'features' => ['rbac_inventory', 'rbac_backup_history'],
            'status' => 'missing',
            'details' => null,
        ],
    ]);

    $rbacCheck = collect($checks)->firstWhere('key', 'permissions.intune_rbac_assignments');

    expect($rbacCheck)->toBeArray();
    expect($rbacCheck['status'] ?? null)->toBe(VerificationCheckStatus::Fail->value);
    expect($rbacCheck['blocking'] ?? null)->toBeTrue();
    expect($rbacCheck['reason_code'] ?? null)->toBe(ProviderReasonCodes::IntuneRbacPermissionMissing);
    expect((string) ($rbacCheck['message'] ?? ''))->toContain('DeviceManagementRBAC.Read.All');
    expect((string) ($rbacCheck['message'] ?? ''))->toContain('RBAC inventory and backup history');
    expect($rbacCheck['next_steps'][0]['url'] ?? null)->toBe(RequiredPermissionsLinks::requiredPermissions($tenant));
});
