<?php

declare(strict_types=1);

use App\Filament\Pages\ChooseWorkspace;
use App\Filament\Pages\EnvironmentDashboard;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentMembership;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('redirects to the workspace managed-tenants landing after selecting a workspace with no tenants', function (): void {
    $user = User::factory()->create();

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

    Livewire::actingAs($user)
        ->test(ChooseWorkspace::class)
        ->call('selectWorkspace', $workspace->getKey())
        ->assertRedirect(route('admin.workspace.managed-environments.index', ['workspace' => $workspace->slug ?? $workspace->getKey()]));
});

it('redirects to the tenant dashboard after selecting a workspace with exactly one tenant', function (): void {
    $user = User::factory()->create();

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

    $tenant = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'workspace_id' => $workspace->getKey(),
    ]);

    ManagedEnvironmentMembership::query()->create([
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'role' => 'owner',
        'source' => 'manual',
        'source_ref' => null,
        'created_by_user_id' => null,
    ]);

    Livewire::actingAs($user)
        ->test(ChooseWorkspace::class)
        ->call('selectWorkspace', $workspace->getKey())
        ->assertRedirect(EnvironmentDashboard::getUrl(tenant: $tenant));
});

it('redirects to choose-environment after selecting a workspace with multiple tenants', function (): void {
    $user = User::factory()->create();

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

    $tenants = ManagedEnvironment::factory()->count(2)->create([
        'status' => 'active',
        'workspace_id' => $workspace->getKey(),
    ]);

    foreach ($tenants as $tenant) {
        ManagedEnvironmentMembership::query()->create([
            'managed_environment_id' => $tenant->getKey(),
            'user_id' => $user->getKey(),
            'role' => 'owner',
            'source' => 'manual',
            'source_ref' => null,
            'created_by_user_id' => null,
        ]);
    }

    Livewire::actingAs($user)
        ->test(ChooseWorkspace::class)
        ->call('selectWorkspace', $workspace->getKey())
        ->assertRedirect(route('admin.workspace.managed-environments.index', ['workspace' => $workspace->slug ?? $workspace->getKey()]));
});

it('prefers the stored intended url after selecting a workspace', function (): void {
    $user = User::factory()->create();

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

    $intendedUrl = (string) parse_url(route('admin.operations.index', ['workspace' => $workspace]), PHP_URL_PATH);

    session()->put(WorkspaceContext::INTENDED_URL_SESSION_KEY, $intendedUrl);

    Livewire::actingAs($user)
        ->test(ChooseWorkspace::class)
        ->call('selectWorkspace', $workspace->getKey())
        ->assertRedirect($intendedUrl);
});

it('clears active tenant context when switching into another workspace', function (): void {
    [$user, $tenantA] = createUserWithTenant(role: 'owner');

    $workspaceB = Workspace::factory()->create();

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

    Filament::setTenant($tenantA, true);

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
            WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
                (string) $tenantA->workspace_id => (int) $tenantA->getKey(),
            ],
        ])
        ->post(route('admin.switch-workspace'), ['workspace_id' => (int) $workspaceB->getKey()])
        ->assertRedirect(route('admin.workspace.managed-environments.index', ['workspace' => $workspaceB->slug ?? $workspaceB->getKey()]));

    expect(Filament::getTenant())->toBeNull();
    expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $workspaceB->getKey());
});
