<?php

declare(strict_types=1);

use App\Filament\Pages\ChooseEnvironment;
use App\Filament\Resources\ManagedEnvironmentResource;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Filament\PanelRegistry;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('only returns active membership tenants for normal users', function (): void {
    $user = User::factory()->create();

    $allowed = ManagedEnvironment::factory()->active()->create(['name' => 'Allowed']);
    $onboarding = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $allowed->workspace_id,
        'name' => 'Onboarding',
    ]);
    $archived = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $allowed->workspace_id,
        'name' => 'Archived',
    ]);

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $allowed->workspace_id,
        'user_id' => (int) $user->getKey(),
        'role' => 'readonly',
    ]);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $allowed->workspace_id);

    /** @var \Filament\Panel $panel */
    $panel = app(PanelRegistry::class)->get('admin');

    $tenants = $user->getTenants($panel);

    expect($tenants)->toHaveCount(1);
    expect($tenants->first()?->getKey())->toBe($allowed->getKey());
    expect($tenants->contains(fn (ManagedEnvironment $tenant): bool => $tenant->name === 'Onboarding'))->toBeFalse();
    expect($tenants->contains(fn (ManagedEnvironment $tenant): bool => $tenant->name === 'Archived'))->toBeFalse();
});

it('returns no tenants for users without active tenant memberships', function (): void {
    $user = User::factory()->create();

    $draft = ManagedEnvironment::factory()->draft()->create(['name' => 'Draft']);
    $archived = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $draft->workspace_id,
        'name' => 'Archived',
    ]);

    /** @var \Filament\Panel $panel */
    $panel = app(PanelRegistry::class)->get('admin');

    expect($user->getTenants($panel))->toHaveCount(0);
});

it('rejects selecting non-active memberships as tenant context', function (): void {
    $user = User::factory()->create();

    $active = ManagedEnvironment::factory()->active()->create(['name' => 'Allowed']);
    $onboarding = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $active->workspace_id,
        'name' => 'Onboarding',
    ]);
    $archived = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $active->workspace_id,
        'name' => 'Archived',
    ]);

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

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

    Livewire::actingAs($user)
        ->test(ChooseEnvironment::class)
        ->call('selectEnvironment', $onboarding->getKey())
        ->assertStatus(404);

    Livewire::actingAs($user)
        ->test(ChooseEnvironment::class)
        ->call('selectEnvironment', $archived->getKey())
        ->assertStatus(404);
});

it('keeps managed-environment global search disabled while selector eligibility stays narrow', function (): void {
    $user = User::factory()->create();

    $draft = ManagedEnvironment::factory()->draft()->create(['name' => 'Search Draft']);
    $onboarding = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $draft->workspace_id,
        'name' => 'Search Onboarding',
    ]);
    $archived = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $draft->workspace_id,
        'name' => 'Search Archived',
    ]);

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

    $this->actingAs($user);

    Filament::setCurrentPanel('admin');
    Filament::setTenant(null, true);
    Filament::bootCurrentPanel();

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

    expect(ManagedEnvironmentResource::getGlobalSearchResults('Search'))->toHaveCount(0);
});

it('does not render onboarding or archived tenants in the header selector on workspace pages', function (): void {
    $activeEnvironment = ManagedEnvironment::factory()->active()->create(['name' => 'Header Active ManagedEnvironment']);
    [$user, $activeEnvironment] = createUserWithTenant(tenant: $activeEnvironment, role: 'owner');

    $onboardingTenant = ManagedEnvironment::factory()->onboarding()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Header Onboarding ManagedEnvironment',
    ]);
    $archivedTenant = ManagedEnvironment::factory()->archived()->create([
        'workspace_id' => (int) $activeEnvironment->workspace_id,
        'name' => 'Header Archived ManagedEnvironment',
    ]);

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

    Filament::setTenant(null, true);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $activeEnvironment->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $activeEnvironment->workspace]))
        ->assertSuccessful()
        ->assertSee('Header Active ManagedEnvironment')
        ->assertDontSee('Header Onboarding ManagedEnvironment')
        ->assertDontSee('Header Archived ManagedEnvironment')
        ->assertSee(__('localization.shell.no_environment_selected'));
});
