<?php

declare(strict_types=1);

use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Services\Providers\ProviderConnectionResolver;
use App\Support\Providers\TargetScope\ProviderConnectionSurfaceSummary;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('resolves provider connections and summaries through one neutral target-scope contract', function (): void {
    config()->set('graph.client_id', 'platform-client-id');
    config()->set('graph.client_secret', 'platform-client-secret');

    [, $tenant] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    $connection = ProviderConnection::factory()
        ->platform()
        ->consentGranted()
        ->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'provider' => 'microsoft',
            'display_name' => 'Spec 281 provider connection',
            'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
            'is_default' => true,
            'is_enabled' => true,
            'verification_status' => 'healthy',
        ]);

    $resolution = app(ProviderConnectionResolver::class)
        ->validateConnection($tenant, 'microsoft', $connection->fresh(['tenant']));
    $summary = ProviderConnectionSurfaceSummary::forConnection($connection->fresh(['tenant']));
    $summaryPayload = $summary->toArray();

    expect($resolution->resolved)->toBeTrue()
        ->and($resolution->targetScope?->toArray())->toMatchArray([
            'provider' => 'microsoft',
            'scope_kind' => 'tenant',
            'scope_identifier' => '11111111-1111-1111-1111-111111111111',
            'shared_label' => 'Target scope',
        ])
        ->and($resolution->targetScope?->toArray())->not->toHaveKey('entra_tenant_id')
        ->and($summaryPayload['provider'])->toBe('microsoft')
        ->and($summaryPayload['target_scope'] ?? [])->toMatchArray([
            'scope_identifier' => '11111111-1111-1111-1111-111111111111',
        ])
        ->and($summaryPayload['provider_context'] ?? [])->toMatchArray([
            'provider' => 'microsoft',
        ])
        ->and($summaryPayload['target_scope'])->not->toHaveKey('entra_tenant_id')
        ->and($summaryPayload['provider_context']['details'][0] ?? [])->toMatchArray([
            'detail_key' => 'microsoft_tenant_id',
            'detail_value' => '11111111-1111-1111-1111-111111111111',
        ]);
});

it('falls back to the managed environment provider scope when the connection tenant identifier is blank', function (): void {
    config()->set('graph.client_id', 'platform-client-id');
    config()->set('graph.client_secret', 'platform-client-secret');

    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Fallback scope environment',
        'managed_environment_id' => '66666666-6666-6666-6666-666666666666',
    ]);

    $connection = ProviderConnection::factory()
        ->platform()
        ->consentGranted()
        ->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'provider' => 'microsoft',
            'display_name' => 'Fallback scope connection',
            'entra_tenant_id' => '',
            'is_default' => true,
            'is_enabled' => true,
            'verification_status' => 'healthy',
        ]);

    $resolution = app(ProviderConnectionResolver::class)
        ->validateConnection($tenant, 'microsoft', $connection->fresh(['tenant']));
    $summaryPayload = ProviderConnectionSurfaceSummary::forConnection($connection->fresh(['tenant']))->toArray();

    expect($resolution->resolved)->toBeTrue()
        ->and($resolution->targetScope?->scopeIdentifier)->toBe('66666666-6666-6666-6666-666666666666')
        ->and($summaryPayload['target_scope'] ?? [])->toMatchArray([
            'scope_identifier' => '66666666-6666-6666-6666-666666666666',
            'scope_display_name' => 'Fallback scope environment',
        ])
        ->and($summaryPayload['provider_context']['details'][0] ?? [])->toMatchArray([
            'detail_key' => 'microsoft_tenant_id',
            'detail_value' => '66666666-6666-6666-6666-666666666666',
        ])
        ->and($summaryPayload['target_scope'])->not->toHaveKey('entra_tenant_id');
});
