<?php

declare(strict_types=1);

use App\Filament\Pages\TenantDashboard;
use App\Models\Tenant;
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 = Tenant::factory()->active()->create(['name' => 'Source Tenant']);
    [$user, $sourceTenant] = createUserWithTenant(tenant: $sourceTenant, role: 'owner');

    $targetWorkspaceTenant = Tenant::factory()->active()->create([
        'name' => 'Target Tenant',
    ]);
    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(TenantDashboard::getUrl(panel: 'tenant', tenant: $targetWorkspaceTenant));
    expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $targetWorkspace->getKey());
});
