<?php

use App\Services\Intune\ManagedEnvironmentRequiredPermissionsViewModelBuilder;

it('filters and sorts permissions by status, type, features, and search', function (): void {
    $permissions = [
        [
            'key' => 'alpha.read',
            'type' => 'application',
            'description' => 'Alpha application permission',
            'features' => ['backup'],
            'status' => 'missing',
            'details' => null,
        ],
        [
            'key' => 'beta.read',
            'type' => 'delegated',
            'description' => 'Beta delegated permission',
            'features' => ['restore'],
            'status' => 'granted',
            'details' => null,
        ],
        [
            'key' => 'gamma.manage',
            'type' => 'application',
            'description' => 'Gamma restore permission',
            'features' => ['backup', 'restore'],
            'status' => 'error',
            'details' => null,
        ],
    ];

    $state = ManagedEnvironmentRequiredPermissionsViewModelBuilder::normalizeFilterState([
        'status' => 'all',
        'type' => 'all',
        'features' => [],
        'search' => '',
    ]);

    $filtered = ManagedEnvironmentRequiredPermissionsViewModelBuilder::applyFilterState($permissions, $state);

    expect(array_column($filtered, 'key'))->toBe([
        'alpha.read',
        'gamma.manage',
        'beta.read',
    ]);

    $missingState = ManagedEnvironmentRequiredPermissionsViewModelBuilder::normalizeFilterState([
        'status' => 'missing',
        'type' => 'all',
        'features' => ['backup'],
        'search' => '',
    ]);

    $missing = ManagedEnvironmentRequiredPermissionsViewModelBuilder::applyFilterState($permissions, $missingState);

    expect(array_column($missing, 'key'))->toBe([
        'alpha.read',
        'gamma.manage',
    ]);

    $presentDelegatedState = ManagedEnvironmentRequiredPermissionsViewModelBuilder::normalizeFilterState([
        'status' => 'present',
        'type' => 'delegated',
        'features' => [],
        'search' => '',
    ]);

    $presentDelegated = ManagedEnvironmentRequiredPermissionsViewModelBuilder::applyFilterState($permissions, $presentDelegatedState);

    expect(array_column($presentDelegated, 'key'))->toBe([
        'beta.read',
    ]);

    $searchState = ManagedEnvironmentRequiredPermissionsViewModelBuilder::normalizeFilterState([
        'status' => 'all',
        'type' => 'all',
        'features' => [],
        'search' => 'RESTORE',
    ]);

    $search = ManagedEnvironmentRequiredPermissionsViewModelBuilder::applyFilterState($permissions, $searchState);

    expect(array_column($search, 'key'))->toBe([
        'gamma.manage',
    ]);
});
