<?php

use App\Services\Graph\AssignmentFilterResolver;
use App\Services\Graph\GraphResponse;
use App\Services\Graph\MicrosoftGraphClient;
use App\Services\Providers\MicrosoftGraphOptionsResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;

uses(RefreshDatabase::class);
beforeEach(function () {
    Cache::flush();
    $this->graphClient = Mockery::mock(MicrosoftGraphClient::class);
    $this->resolver = new AssignmentFilterResolver($this->graphClient, app(MicrosoftGraphOptionsResolver::class));
});

test('resolves assignment filters by id', function () {
    $filters = [
        ['id' => 'filter-1', 'displayName' => 'Targeted Devices'],
        ['id' => 'filter-2', 'displayName' => 'Excluded Devices'],
    ];

    $response = new GraphResponse(
        success: true,
        data: ['value' => $filters]
    );

    $this->graphClient
        ->shouldReceive('request')
        ->once()
        ->with('GET', '/deviceManagement/assignmentFilters', [
            'query' => [
                '$select' => 'id,displayName',
            ],
        ])
        ->andReturn($response);

    $result = $this->resolver->resolve(['filter-1']);

    expect($result)->toHaveCount(1)
        ->and($result[0]['id'])->toBe('filter-1')
        ->and($result[0]['displayName'])->toBe('Targeted Devices');
});

test('uses cache for repeated lookups', function () {
    $filters = [
        ['id' => 'filter-1', 'displayName' => 'Targeted Devices'],
    ];

    $response = new GraphResponse(
        success: true,
        data: ['value' => $filters]
    );

    $this->graphClient
        ->shouldReceive('request')
        ->once()
        ->andReturn($response);

    $result1 = $this->resolver->resolve(['filter-1']);
    $result2 = $this->resolver->resolve(['filter-1']);

    expect($result1)->toBe($result2);
});
