<?php

declare(strict_types=1);

use App\Filament\Pages\Workspaces\ManagedEnvironmentOnboardingWizard;
use App\Livewire\BulkOperationProgress;
use App\Models\ManagedEnvironment;
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('shows the onboarding start state when no resumable drafts exist', 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)
        ->get(route('admin.onboarding'))
        ->assertSuccessful()
        ->assertSee('Create or resume a managed environment in this workspace.')
        ->assertDontSeeLivewire(BulkOperationProgress::class)
        ->assertDontSee('Multiple onboarding drafts are available.');
});

it('redirects the landing route to the only resumable draft', 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());

    $draft = createOnboardingDraft([
        'workspace' => $workspace,
        'started_by' => $user,
        'updated_by' => $user,
        'state' => [
            'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
            'environment_name' => 'Contoso',
            'environment' => 'prod',
        ],
    ]);

    $this->actingAs($user)
        ->get(route('admin.onboarding'))
        ->assertRedirect(route('admin.onboarding.draft', ['onboardingDraft' => $draft->getKey()]));
});

it('loads a concrete draft route with confirmed persisted state', function (): void {
    $workspace = Workspace::factory()->create();
    $tenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => '22222222-2222-2222-2222-222222222222',
        'name' => 'Contoso GmbH',
        'status' => ManagedEnvironment::STATUS_ONBOARDING,
    ]);
    $user = User::factory()->create();

    createUserWithTenant(
        tenant: $tenant,
        user: $user,
        role: 'owner',
        workspaceRole: 'owner',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    $draft = createOnboardingDraft([
        'workspace' => $workspace,
        'tenant' => $tenant,
        'started_by' => $user,
        'updated_by' => $user,
        'current_step' => 'connection',
        'state' => [
            'entra_tenant_id' => (string) $tenant->managed_environment_id,
            'environment_name' => (string) $tenant->name,
            'environment' => 'prod',
            'primary_domain' => 'contoso.example',
            'notes' => 'Confirmed draft state',
        ],
    ]);

    $this->actingAs($user)
        ->get(route('admin.onboarding.draft', ['onboardingDraft' => $draft->getKey()]))
        ->assertSuccessful()
        ->assertDontSeeLivewire(BulkOperationProgress::class)
        ->assertSee('Onboarding draft')
        ->assertSee('Contoso GmbH')
        ->assertSee('22222222-2222-2222-2222-222222222222')
        ->assertSee('Started by')
        ->assertSee($user->name);
});

it('hides the all drafts header action when the current draft is the only resumable draft', 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());

    $draft = createOnboardingDraft([
        'workspace' => $workspace,
        'started_by' => $user,
        'updated_by' => $user,
        'state' => [
            'entra_tenant_id' => '77777777-7777-7777-7777-777777777777',
            'environment_name' => 'Single Draft ManagedEnvironment',
            'environment' => 'prod',
        ],
    ]);

    $this->actingAs($user)
        ->get(route('admin.onboarding.draft', ['onboardingDraft' => $draft->getKey()]))
        ->assertSuccessful()
        ->assertDontSee('Choose onboarding draft');
});

it('shows the all drafts header action when multiple resumable drafts exist', 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());

    createOnboardingDraft([
        'workspace' => $workspace,
        'started_by' => $user,
        'updated_by' => $user,
        'state' => [
            'entra_tenant_id' => '88888888-8888-8888-8888-888888888888',
            'environment_name' => 'First Draft ManagedEnvironment',
            'environment' => 'prod',
        ],
    ]);

    $draft = createOnboardingDraft([
        'workspace' => $workspace,
        'started_by' => $user,
        'updated_by' => $user,
        'state' => [
            'entra_tenant_id' => '99999999-9999-9999-9999-999999999999',
            'environment_name' => 'Second Draft ManagedEnvironment',
            'environment' => 'staging',
        ],
    ]);

    $this->actingAs($user)
        ->get(route('admin.onboarding.draft', ['onboardingDraft' => $draft->getKey()]))
        ->assertSuccessful()
        ->assertSee('Choose onboarding draft');
});

it('redirects to the canonical draft route immediately after step one identifies a tenant', 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());

    Livewire::actingAs($user)
        ->test(ManagedEnvironmentOnboardingWizard::class)
        ->call('identifyManagedEnvironment', [
            'entra_tenant_id' => '33333333-3333-3333-3333-333333333333',
            'environment' => 'prod',
            'name' => 'Canonical Draft ManagedEnvironment',
        ])
        ->assertRedirect(route('admin.onboarding.draft', [
            'onboardingDraft' => ManagedEnvironmentOnboardingSession::query()
                ->where('workspace_id', (int) $workspace->getKey())
                ->where('entra_tenant_id', '33333333-3333-3333-3333-333333333333')
                ->value('id'),
        ]));
});
