<?php

use App\Filament\Resources\TenantResource;
use App\Models\ProviderConnection;
use App\Models\ProviderCredential;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);
it('includes scope parameter in admin consent url', function () {
    // The adminConsentUrl uses `.default` so the tenant consents to configured app permissions.
    $tenant = Tenant::create([
        'tenant_id' => 'b0091e5d-944f-4a34-bcd9-12cbfb7b75cf',
        'name' => 'Test Tenant',
        'app_client_id' => 'client-id',
    ]);

    $url = TenantResource::adminConsentUrl($tenant);

    expect($url)
        ->toContain('scope=')
        ->toContain(urlencode('https://graph.microsoft.com/.default'));
});

it('can derive admin consent url from provider connection credentials when tenant app_client_id is missing', function () {
    $tenant = Tenant::factory()->create([
        'app_client_id' => null,
    ]);

    $connection = ProviderConnection::factory()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'provider' => 'microsoft',
        'entra_tenant_id' => (string) $tenant->graphTenantId(),
        'is_default' => true,
    ]);

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

    $url = TenantResource::adminConsentUrl($tenant);

    expect($url)
        ->not->toBeNull()
        ->and($url)->toContain('login.microsoftonline.com')
        ->and($url)->toContain('adminconsent')
        ->and($url)->toContain(urlencode('derived-client-id'));
});
