<?php

declare(strict_types=1);

use App\Filament\Pages\EnvironmentDashboard;
use App\Models\ManagedEnvironment;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('ignores an intended tenant route that is not valid in the target workspace', function (): void {
    $sourceTenant = ManagedEnvironment::factory()->active()->create(['name' => 'Source ManagedEnvironment']);
    [$user, $sourceTenant] = createUserWithTenant(tenant: $sourceTenant, role: 'owner');

    $targetWorkspaceTenant = ManagedEnvironment::factory()->active()->create([
        'name' => 'Target ManagedEnvironment',
    ]);
    createUserWithTenant(tenant: $targetWorkspaceTenant, user: $user, role: 'owner');

    $targetWorkspace = $targetWorkspaceTenant->workspace()->firstOrFail();

    $response = $this->actingAs($user)
        ->withSession([
            WorkspaceContext::SESSION_KEY => (int) $sourceTenant->workspace_id,
            WorkspaceContext::INTENDED_URL_SESSION_KEY => "/admin/t/{$sourceTenant->external_id}",
        ])
        ->post(route('admin.switch-workspace'), [
            'workspace_id' => (int) $targetWorkspace->getKey(),
        ]);

    $response->assertRedirect(EnvironmentDashboard::getUrl(panel: 'admin', tenant: $targetWorkspaceTenant));
    expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $targetWorkspace->getKey());
});
