<?php

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

uses(RefreshDatabase::class);

test('choosing a tenant persists last used tenant preference', function () {
    $first = ManagedEnvironment::factory()->create([
        'status' => 'active',
    ]);

    $second = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $first->workspace_id,
        'status' => 'active',
    ]);

    $user = User::factory()->create();
    $this->actingAs($user);

    createUserWithTenant(tenant: $first, user: $user, role: 'owner');
    createUserWithTenant(tenant: $second, user: $user, role: 'owner');

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

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

    $preference = UserTenantPreference::query()
        ->where('user_id', $user->getKey())
        ->where('managed_environment_id', $second->getKey())
        ->first();

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