<?php

use App\Services\Graph\GraphContractRegistry;
use App\Services\Graph\GraphLogger;
use App\Services\Graph\MicrosoftGraphClient;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;

it('falls back to default graph scope when config is empty', function () {
    Cache::flush();

    Config::set('graph.scope', '');
    Config::set('graph.managed_environment_id', 'tenant-scope');
    Config::set('graph.client_id', 'client-id');
    Config::set('graph.client_secret', 'client-secret');

    Http::fake([
        'https://login.microsoftonline.com/*/oauth2/v2.0/token' => Http::response([
            'access_token' => 'token',
            'expires_in' => 3600,
            'token_type' => 'Bearer',
        ]),
        'https://graph.microsoft.com/*' => Http::response(['value' => []]),
    ]);

    $client = new MicrosoftGraphClient(
        app(GraphLogger::class),
        app(GraphContractRegistry::class)
    );

    $client->getOrganization();

    Http::assertSent(function (Request $request): bool {
        if (! str_contains($request->url(), '/oauth2/v2.0/token')) {
            return false;
        }

        return $request['scope'] === 'https://graph.microsoft.com/.default'
            && $request['client_id'] === 'client-id'
            && $request['grant_type'] === 'client_credentials';
    });
});
