<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Models\User;
use App\Support\OperateHub\OperateHubShell;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;

uses(RefreshDatabase::class);

it('prefers a valid tenant query hint over remembered tenant state on workspace-scoped admin routes', function (): void {
    $rememberedTenant = Tenant::factory()->active()->create(['name' => 'Remembered Tenant']);
    [$user, $rememberedTenant] = createUserWithTenant(tenant: $rememberedTenant, role: 'owner');

    $hintedTenant = Tenant::factory()->active()->create([
        'workspace_id' => (int) $rememberedTenant->workspace_id,
        'name' => 'Hinted Tenant',
    ]);

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

    $this->actingAs($user);
    Filament::setTenant(null, true);

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

    session()->put(WorkspaceContext::SESSION_KEY, $workspaceId);
    session()->put(WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY, [
        (string) $workspaceId => (int) $rememberedTenant->getKey(),
    ]);

    $request = Request::create(route('admin.operations.index', ['tenant' => $hintedTenant->external_id]));
    $request->setLaravelSession(app('session.store'));
    $request->setUserResolver(static fn () => $user);

    $route = app('router')->getRoutes()->match($request);
    $request->setRouteResolver(static fn () => $route);

    $resolved = app(OperateHubShell::class)->resolvedContext($request);

    expect($resolved->workspace?->getKey())->toBe($workspaceId)
        ->and($resolved->tenant?->is($hintedTenant))->toBeTrue()
        ->and($resolved->tenantSource)->toBe('query_hint')
        ->and($resolved->state)->toBe('tenant_scoped');
});

it('falls back to a tenantless workspace state when a tenant query hint targets another workspace', function (): void {
    $workspaceTenant = Tenant::factory()->active()->create(['name' => 'Current Workspace Tenant']);
    [$user, $workspaceTenant] = createUserWithTenant(tenant: $workspaceTenant, role: 'owner');

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

    $this->actingAs($user);
    Filament::setTenant(null, true);

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

    session()->put(WorkspaceContext::SESSION_KEY, $workspaceId);

    $request = Request::create(route('admin.operations.index', ['tenant' => $foreignTenant->external_id]));
    $request->setLaravelSession(app('session.store'));
    $request->setUserResolver(static fn () => $user);

    $route = app('router')->getRoutes()->match($request);
    $request->setRouteResolver(static fn () => $route);

    $resolved = app(OperateHubShell::class)->resolvedContext($request);

    expect($resolved->workspace?->getKey())->toBe($workspaceId)
        ->and($resolved->tenant)->toBeNull()
        ->and($resolved->state)->toBe('tenantless_workspace')
        ->and($resolved->recoveryReason)->toBe('mismatched_workspace');
});

it('uses the routed tenant workspace when the tenant panel is entered without a selected workspace session', function (): void {
    $tenant = Tenant::factory()->active()->create(['name' => 'Tenant Panel Scope']);
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $this->actingAs($user);
    Filament::setTenant(null, true);

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

    $request = Request::create("/admin/t/{$tenant->external_id}");
    $request->setLaravelSession(app('session.store'));
    $request->setUserResolver(static fn () => $user);

    $route = app('router')->getRoutes()->match($request);
    $request->setRouteResolver(static fn () => $route);

    $resolved = app(OperateHubShell::class)->resolvedContext($request);

    expect($resolved->workspace?->getKey())->toBe((int) $tenant->workspace_id)
        ->and($resolved->tenant?->is($tenant))->toBeTrue()
        ->and($resolved->workspaceSource)->toBe('route')
        ->and($resolved->tenantSource)->toBe('route');
});
