<?php

declare(strict_types=1);

use App\Filament\Pages\ChooseEnvironment;
use App\Filament\Pages\EnvironmentDashboard;
use App\Models\ManagedEnvironment;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('shows only active tenants in the standard chooser and persists the last-used tenant', function (): void {
    $activeEnvironment = ManagedEnvironment::factory()->active()->create(['name' => 'Active ManagedEnvironment']);
    [$user, $activeEnvironment] = createUserWithTenant(tenant: $activeEnvironment, role: 'owner');

    $this->actingAs($user);

    $otherActiveTenant = ManagedEnvironment::factory()->active()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Other Active ManagedEnvironment',
    ]);
    $onboardingTenant = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Onboarding ManagedEnvironment',
    ]);
    $draftTenant = ManagedEnvironment::factory()->draft()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Draft ManagedEnvironment',
    ]);
    $archivedTenant = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Archived ManagedEnvironment',
    ]);

    createUserWithTenant(tenant: $otherActiveTenant, user: $user, role: 'owner');
    createUserWithTenant(tenant: $onboardingTenant, user: $user, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
    createUserWithTenant(tenant: $draftTenant, user: $user, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);
    createUserWithTenant(tenant: $archivedTenant, user: $user, role: 'owner', ensureDefaultMicrosoftProviderConnection: false);

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

    $this->get('/admin/choose-environment')
        ->assertSuccessful()
        ->assertSee('Active ManagedEnvironment')
        ->assertSee('Other Active ManagedEnvironment')
        ->assertDontSee('Onboarding ManagedEnvironment')
        ->assertDontSee('Draft ManagedEnvironment')
        ->assertDontSee('Archived ManagedEnvironment');

    Livewire::test(ChooseEnvironment::class)
        ->call('selectEnvironment', (int) $activeEnvironment->getKey())
        ->assertRedirect(EnvironmentDashboard::getUrl(tenant: $activeEnvironment));

    $user->refresh();

    if (Schema::hasColumn('users', 'last_tenant_id')) {
        expect($user->last_tenant_id)->toBe($activeEnvironment->getKey());

        return;
    }

    if (Schema::hasTable('user_managed_environment_preferences')) {
        $preference = $user->tenantPreferences()
            ->where('managed_environment_id', $activeEnvironment->getKey())
            ->first();

        expect($preference)->not->toBeNull();
        expect($preference?->last_used_at)->not->toBeNull();
    }
});

it('returns 404 when a non-operable tenant is selected through the chooser endpoint', function (): void {
    $tenant = ManagedEnvironment::factory()->onboarding()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
        ->post(route('admin.select-environment'), ['managed_environment_id' => (int) $tenant->getKey()])
        ->assertNotFound();
});
