<?php

declare(strict_types=1);

use App\Filament\Pages\Workspaces\ManagedEnvironmentOnboardingWizard;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('reuses the provider connection surface summary in onboarding readiness', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

    $connection = ProviderConnection::factory()->consentGranted()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'provider' => 'microsoft',
        'display_name' => 'Spec 281 onboarding connection',
        'entra_tenant_id' => '77777777-7777-7777-7777-777777777777',
        'is_default' => true,
        'verification_status' => 'healthy',
    ]);

    $draft = ManagedEnvironmentOnboardingSession::query()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'managed_environment_id' => (int) $tenant->getKey(),
        'entra_tenant_id' => '77777777-7777-7777-7777-777777777777',
        'current_step' => 'connection',
        'state' => [
            'provider_connection_id' => (int) $connection->getKey(),
        ],
        'started_by_user_id' => (int) $user->getKey(),
        'updated_by_user_id' => (int) $user->getKey(),
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $tenant->workspace_id);

    $component = Livewire::actingAs($user)
        ->test(ManagedEnvironmentOnboardingWizard::class, ['onboardingDraft' => (int) $draft->getKey()]);

    $method = new ReflectionMethod($component->instance(), 'readinessProviderSummary');
    $method->setAccessible(true);

    $summary = $method->invoke($component->instance(), $connection->fresh(['tenant']));

    expect($summary['provider'])->toBe('microsoft')
        ->and($summary['target_scope'] ?? [])->toMatchArray([
            'scope_identifier' => '77777777-7777-7777-7777-777777777777',
            'shared_label' => 'Target scope',
        ])
        ->and($summary['target_scope_summary'] ?? null)->toBe($tenant->name.' (77777777-7777-7777-7777-777777777777)')
        ->and($summary['provider_context'] ?? [])->toMatchArray([
            'provider' => 'microsoft',
        ])
        ->and($summary['target_scope'])->not->toHaveKey('entra_tenant_id')
        ->and($summary)->not->toHaveKey('contextual_identity_details');
});
