<?php

use App\Models\ProviderConnection;
use App\Models\ProviderCredential;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse;
use App\Services\Providers\ProviderGateway;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('builds per-request graph context from a provider connection + credentials', function (): void {
    $connection = ProviderConnection::factory()->dedicated()->create([
        'entra_tenant_id' => 'entra-tenant-id',
    ]);

    ProviderCredential::factory()->create([
        'provider_connection_id' => $connection->getKey(),
        'payload' => [
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
        ],
    ]);

    $graph = new class implements GraphClientInterface
    {
        public array $calls = [];

        public function listPolicies(string $policyType, array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'listPolicies', 'policyType' => $policyType, 'options' => $options];

            return new GraphResponse(true);
        }

        public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'getPolicy', 'policyType' => $policyType, 'policyId' => $policyId, 'options' => $options];

            return new GraphResponse(true);
        }

        public function getOrganization(array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'getOrganization', 'options' => $options];

            return new GraphResponse(true);
        }

        public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'applyPolicy', 'policyType' => $policyType, 'policyId' => $policyId, 'payload' => $payload, 'options' => $options];

            return new GraphResponse(true);
        }

        public function getServicePrincipalPermissions(array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'getServicePrincipalPermissions', 'options' => $options];

            return new GraphResponse(true);
        }

        public function request(string $method, string $path, array $options = []): GraphResponse
        {
            $this->calls[] = ['fn' => 'request', 'method' => $method, 'path' => $path, 'options' => $options];

            return new GraphResponse(true);
        }
    };

    $gateway = app()->make(ProviderGateway::class, [
        'graph' => $graph,
    ]);

    $gateway->getOrganization($connection);
    $gateway->getPolicy($connection, 'deviceConfiguration', 'policy-1', ['platform' => 'windows']);
    $gateway->applyPolicy($connection, 'deviceConfiguration', 'policy-1', ['displayName' => 'Policy'], ['method' => 'PATCH']);
    $gateway->getServicePrincipalPermissions($connection, ['query' => ['$select' => 'id']]);
    $gateway->request($connection, 'GET', 'organization', ['query' => ['a' => 'b']]);

    expect($graph->calls)->toHaveCount(5);

    $first = $graph->calls[0]['options'];
    $second = $graph->calls[1]['options'];
    $third = $graph->calls[2]['options'];
    $fourth = $graph->calls[3]['options'];
    $fifth = $graph->calls[4]['options'];

    expect($first['tenant'])->toBe('entra-tenant-id');
    expect($first['client_id'])->toBe('client-id');
    expect($first['client_secret'])->toBe('client-secret');
    expect($first['client_request_id'])->toBeString()->not->toBeEmpty();

    expect($second['tenant'])->toBe('entra-tenant-id');
    expect($second['client_id'])->toBe('client-id');
    expect($second['client_secret'])->toBe('client-secret');
    expect($second['client_request_id'])->toBeString()->not->toBeEmpty();
    expect($second['platform'])->toBe('windows');

    expect($third['tenant'])->toBe('entra-tenant-id');
    expect($third['client_id'])->toBe('client-id');
    expect($third['client_secret'])->toBe('client-secret');
    expect($third['client_request_id'])->toBeString()->not->toBeEmpty();
    expect($third['method'])->toBe('PATCH');

    expect($fourth['tenant'])->toBe('entra-tenant-id');
    expect($fourth['client_id'])->toBe('client-id');
    expect($fourth['client_secret'])->toBe('client-secret');
    expect($fourth['client_request_id'])->toBeString()->not->toBeEmpty();
    expect($fourth['query'])->toBe(['$select' => 'id']);

    expect($fifth['tenant'])->toBe('entra-tenant-id');
    expect($fifth['client_id'])->toBe('client-id');
    expect($fifth['client_secret'])->toBe('client-secret');
    expect($fifth['client_request_id'])->toBeString()->not->toBeEmpty();
    expect($fifth['query'])->toBe(['a' => 'b']);
});

it('builds per-request graph context from the central platform identity for platform connections', function (): void {
    config()->set('graph.client_id', 'platform-client-id');
    config()->set('graph.client_secret', 'platform-client-secret');

    $connection = ProviderConnection::factory()->platform()->create([
        'entra_tenant_id' => 'entra-tenant-id',
    ]);

    ProviderCredential::factory()->create([
        'provider_connection_id' => $connection->getKey(),
        'payload' => [
            'client_id' => 'dedicated-fallback-client-id',
            'client_secret' => 'dedicated-fallback-client-secret',
        ],
    ]);

    $graph = new class implements GraphClientInterface
    {
        /** @var array<string, mixed> */
        public array $lastOptions = [];

        public function listPolicies(string $policyType, array $options = []): GraphResponse
        {
            return new GraphResponse(true);
        }

        public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse
        {
            return new GraphResponse(true);
        }

        public function getOrganization(array $options = []): GraphResponse
        {
            $this->lastOptions = $options;

            return new GraphResponse(true);
        }

        public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse
        {
            return new GraphResponse(true);
        }

        public function getServicePrincipalPermissions(array $options = []): GraphResponse
        {
            return new GraphResponse(true);
        }

        public function request(string $method, string $path, array $options = []): GraphResponse
        {
            return new GraphResponse(true);
        }
    };

    $gateway = app()->make(ProviderGateway::class, [
        'graph' => $graph,
    ]);

    $gateway->getOrganization($connection);

    expect($graph->lastOptions['tenant'] ?? null)->toBe('entra-tenant-id')
        ->and($graph->lastOptions['client_id'] ?? null)->toBe('platform-client-id')
        ->and($graph->lastOptions['client_secret'] ?? null)->toBe('platform-client-secret')
        ->and($graph->lastOptions['client_id'] ?? null)->not->toBe('dedicated-fallback-client-id')
        ->and($graph->lastOptions['client_request_id'] ?? null)->toBeString()->not->toBeEmpty();
});

it('owns graph request option assembly for resolved provider identities', function (): void {
    $connection = ProviderConnection::factory()->dedicated()->create([
        'entra_tenant_id' => 'entra-tenant-id',
    ]);

    ProviderCredential::factory()->create([
        'provider_connection_id' => $connection->getKey(),
        'payload' => [
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
        ],
    ]);

    $gateway = app(ProviderGateway::class);

    $options = $gateway->graphOptions($connection, [
        'query' => ['$select' => 'id'],
    ]);

    expect($options)->toMatchArray([
        'tenant' => 'entra-tenant-id',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'query' => ['$select' => 'id'],
    ]);
    expect($options['client_request_id'])->toBeString()->not->toBeEmpty();
});
