<?php

use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\ManagedEnvironmentLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('default Filament tenant selection respects current workspace context', function () {
    $user = User::factory()->create();

    $workspaceA = Workspace::factory()->create(['name' => 'Workspace A']);
    $workspaceB = Workspace::factory()->create(['name' => 'Workspace B']);

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

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

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

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

    $user->tenants()->syncWithoutDetaching([
        $tenantA->getKey() => ['role' => 'owner'],
        $tenantB->getKey() => ['role' => 'owner'],
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspaceA->getKey());
    $user->forceFill(['last_workspace_id' => (int) $workspaceA->getKey()])->save();

    $this->actingAs($user)
        ->get(route('filament.admin.pages.choose-environment'))
        ->assertOk()
        ->assertSee($tenantA->name)
        ->assertDontSee($tenantB->name);
});

test('user menu does not render a workspace switcher (topbar context bar is the single entry point)', function () {
    [$user, $tenant] = createUserWithTenant();

    $workspace = Workspace::query()->whereKey($tenant->workspace_id)->firstOrFail();

    $this->actingAs($user)
        ->get(ManagedEnvironmentLinks::indexUrl($tenant))
        ->assertOk()
        ->assertSee($workspace->name)
        ->assertDontSee('name="workspace_id"', escape: false);
});

test('workspace-wide operations keep shell scope tenantless when a valid tenant query filter is present', function () {
    $rememberedEnvironment = ManagedEnvironment::factory()->create([
        'workspace_id' => null,
        'status' => 'active',
        'name' => 'Remembered Topbar ManagedEnvironment',
    ]);
    [$user, $rememberedEnvironment] = createUserWithTenant(tenant: $rememberedEnvironment, role: 'owner');

    $hintedTenant = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $rememberedEnvironment->workspace_id,
        'status' => 'active',
        'name' => 'Hinted Topbar ManagedEnvironment',
    ]);

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

    Filament::setTenant(null, true);

    $workspaceId = (int) $rememberedEnvironment->workspace_id;

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => $workspaceId,
            WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
                (string) $workspaceId => (int) $rememberedEnvironment->getKey(),
            ],
        ])
        ->get(route('admin.operations.index', ['workspace' => $workspaceId, 'environment_id' => (int) $hintedTenant->getKey()]))
        ->assertOk()
        ->assertSee(__('localization.shell.no_environment_selected'))
        ->assertSee(__('localization.shell.all_environments'))
        ->assertDontSee(__('localization.shell.environment_scope').': Hinted Topbar ManagedEnvironment')
        ->assertDontSee(__('localization.shell.environment_scope').': Remembered Topbar ManagedEnvironment');
});
