<?php

declare(strict_types=1);

use App\Filament\Pages\EnvironmentDashboard;
use App\Filament\Pages\Governance\DecisionRegister;
use App\Filament\Pages\Governance\GovernanceInbox;
use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('shows the routed workspace and tenant truth on workspace-first environment entry without relying on session workspace state', function (): void {
    $tenant = ManagedEnvironment::factory()->active()->create(['name' => 'ManagedEnvironment Panel Entry']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    session()->forget(WorkspaceContext::SESSION_KEY);

    $this->actingAs($user)
        ->get(EnvironmentDashboard::getUrl(tenant: $tenant))
        ->assertOk()
        ->assertSee($tenant->workspace()->firstOrFail()->name)
        ->assertSee('ManagedEnvironment Panel Entry')
        ->assertSee(__('localization.shell.switch_environment'))
        ->assertSee(__('localization.shell.clear_environment_scope'))
        ->assertDontSee(__('localization.shell.search_environments'))
        ->assertDontSee('admin/select-environment');
});

it('keeps workspace-scoped routes tenantless when a cross-workspace tenant hint is rejected', function (): void {
    $workspaceTenant = ManagedEnvironment::factory()->active()->create(['name' => 'Workspace ManagedEnvironment']);
    [$user, $workspaceTenant] = createUserWithTenant(tenant: $workspaceTenant, role: 'owner');

    $foreignTenant = ManagedEnvironment::factory()->active()->create(['name' => 'Rejected Foreign ManagedEnvironment']);
    createUserWithTenant(tenant: $foreignTenant, user: User::factory()->create(), role: 'owner');

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceTenant->workspace_id])
        ->get(route('admin.operations.index', ['workspace' => $workspaceTenant->workspace, 'tenant' => $foreignTenant->external_id]))
        ->assertOk()
        ->assertSee(__('localization.shell.no_environment_selected'))
        ->assertDontSee(__('localization.shell.environment_scope').': Rejected Foreign ManagedEnvironment');
});

it('keeps workspace-wide surfaces tenantless when valid environment query filters are present', function (string $surface, callable $urlFactory): void {
    $rememberedEnvironment = ManagedEnvironment::factory()->active()->create([
        'name' => 'Remembered ManagedEnvironment',
        'external_id' => 'remembered-managed-environment',
    ]);
    [$user, $rememberedEnvironment] = createUserWithTenant(tenant: $rememberedEnvironment, role: 'owner');

    $hintedTenant = ManagedEnvironment::factory()->active()->create([
        'workspace_id' => (int) $rememberedEnvironment->workspace_id,
        'name' => 'Hinted ManagedEnvironment',
        'external_id' => 'hinted-managed-environment',
    ]);

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

    Filament::setTenant($rememberedEnvironment, true);

    $workspace = $rememberedEnvironment->workspace()->firstOrFail();
    $url = $urlFactory($workspace, $hintedTenant);

    $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $workspace->getKey(),
            WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
                (string) $workspace->getKey() => (int) $rememberedEnvironment->getKey(),
            ],
        ])
        ->followingRedirects()
        ->get($url)
        ->assertOk()
        ->assertSee(__('localization.shell.no_environment_selected'))
        ->assertDontSee(__('localization.shell.environment_scope').': Hinted ManagedEnvironment')
        ->assertDontSee(__('localization.shell.environment_scope').': Remembered ManagedEnvironment')
        ->assertDontSee('Back to Hinted ManagedEnvironment')
        ->assertDontSee('Back to Remembered ManagedEnvironment');
})->with([
    'operations' => [
        'operations',
        fn ($workspace, ManagedEnvironment $tenant): string => route('admin.operations.index', [
            'workspace' => $workspace,
            'managed_environment_id' => (int) $tenant->getKey(),
        ]),
    ],
    'customer review workspace' => [
        'customer review workspace',
        fn ($workspace, ManagedEnvironment $tenant): string => CustomerReviewWorkspace::getUrl(panel: 'admin', parameters: [
            'tenant' => (string) $tenant->external_id,
        ]),
    ],
    'decision register' => [
        'decision register',
        fn ($workspace, ManagedEnvironment $tenant): string => DecisionRegister::getUrl(panel: 'admin', parameters: [
            'managed_environment_id' => (string) $tenant->getKey(),
        ]),
    ],
    'governance inbox' => [
        'governance inbox',
        fn ($workspace, ManagedEnvironment $tenant): string => GovernanceInbox::getUrl(panel: 'admin', parameters: [
            'managed_environment_id' => (string) $tenant->getKey(),
        ]),
    ],
    'audit log' => [
        'audit log',
        fn ($workspace, ManagedEnvironment $tenant): string => route('admin.monitoring.audit-log', [
            'managed_environment_id' => (int) $tenant->getKey(),
        ]),
    ],
    'provider connections' => [
        'provider connections',
        fn ($workspace, ManagedEnvironment $tenant): string => ProviderConnectionResource::getUrl('index', [
            'managed_environment_id' => (string) $tenant->external_id,
        ], panel: 'admin'),
    ],
    'alerts' => [
        'alerts',
        fn ($workspace, ManagedEnvironment $tenant): string => route('filament.admin.alerts', [
            'tenant' => (string) $tenant->external_id,
        ]),
    ],
    'workspace overview' => [
        'workspace overview',
        fn ($workspace, ManagedEnvironment $tenant): string => route('admin.workspace.home', [
            'workspace' => $workspace,
            'tenant' => (string) $tenant->external_id,
        ]),
    ],
]);
