<?php

declare(strict_types=1);

use App\Filament\Pages\ChooseTenant;
use App\Filament\Pages\TenantDashboard;
use App\Models\Tenant;
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 {
    $activeTenant = Tenant::factory()->active()->create(['name' => 'Active Tenant']);
    [$user, $activeTenant] = createUserWithTenant(tenant: $activeTenant, role: 'owner');

    $this->actingAs($user);

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

    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) $activeTenant->workspace_id);

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

    Livewire::test(ChooseTenant::class)
        ->call('selectTenant', (int) $activeTenant->getKey())
        ->assertRedirect(TenantDashboard::getUrl(tenant: $activeTenant));

    $user->refresh();

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

        return;
    }

    if (Schema::hasTable('user_tenant_preferences')) {
        $preference = $user->tenantPreferences()
            ->where('tenant_id', $activeTenant->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 = Tenant::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-tenant'), ['tenant_id' => (int) $tenant->getKey()])
        ->assertNotFound();
});
