<?php

declare(strict_types=1);

use App\Filament\Pages\Workspaces\ManagedEnvironmentOnboardingWizard;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Livewire\Livewire;

it('never persists client secrets in onboarding session state and never pre-fills them on resume', function (): void {
    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'owner',
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    $this->actingAs($user);

    $entraTenantId = '66666666-6666-6666-6666-666666666666';
    $secret = 'super-secret-client-secret';

    Livewire::actingAs($user)
        ->test(ManagedEnvironmentOnboardingWizard::class)
        ->call('identifyManagedEnvironment', [
            'entra_tenant_id' => $entraTenantId,
            'environment' => 'prod',
            'name' => 'Acme',
        ])
        ->call('createProviderConnection', [
            'display_name' => 'Acme connection',
            'client_id' => '00000000-0000-0000-0000-000000000000',
            'client_secret' => $secret,
            'is_default' => true,
        ]);

    $session = ManagedEnvironmentOnboardingSession::query()
        ->where('workspace_id', (int) $workspace->getKey())
        ->where('entra_tenant_id', $entraTenantId)
        ->whereNull('completed_at')
        ->firstOrFail();

    $encodedState = json_encode($session->state, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    expect($encodedState)->not->toContain($secret);
    expect($session->state)->not->toHaveKey('client_secret');
    expect($session->state)->not->toHaveKey('new_connection');

    $resumed = Livewire::actingAs($user)->test(ManagedEnvironmentOnboardingWizard::class);

    $data = $resumed->get('data');

    expect($data['new_connection']['client_secret'] ?? null)->toBeNull();
});
