<?php

declare(strict_types=1);

use App\Filament\Pages\EnvironmentDashboard;
use App\Support\PortfolioTriage\PortfolioArrivalContextResolver;
use App\Support\PortfolioTriage\PortfolioArrivalContextToken;
use App\Support\RestoreSafety\RestoreResultAttention;
use App\Support\Tenants\TenantRecoveryTriagePresentation;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tests\Feature\Concerns\BuildsPortfolioTriageFixtures;

uses(BuildsPortfolioTriageFixtures::class);

function performanceArrivalRequest(array $query, int $workspaceId): Request
{
    $request = Request::create('/admin/t/test-tenant', 'GET', $query);
    $session = app('session.store');
    $session->start();
    $session->put(WorkspaceContext::SESSION_KEY, $workspaceId);
    $request->setLaravelSession($session);

    return $request;
}

it('memoizes arrival-context resolution within a single request', function (): void {
    [$user, $tenant] = $this->makePortfolioTriageActor('Performance ManagedEnvironment');
    $this->seedPortfolioRecoveryConcern($tenant, RestoreResultAttention::STATE_COMPLETED_WITH_FOLLOW_UP);
    $this->actingAs($user);

    $request = performanceArrivalRequest([
        PortfolioArrivalContextToken::QUERY_PARAMETER => PortfolioArrivalContextToken::encode([
            'sourceSurface' => PortfolioArrivalContextToken::SOURCE_TENANT_REGISTRY,
            'tenantRouteKey' => (string) $tenant->external_id,
            'workspaceId' => (int) $tenant->workspace_id,
            'concernFamily' => PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE,
            'concernState' => TenantRecoveryTriagePresentation::RECOVERY_EVIDENCE_WEAKENED,
            'concernReason' => RestoreResultAttention::STATE_COMPLETED_WITH_FOLLOW_UP,
            'returnFilters' => [
                'recovery_evidence' => [TenantRecoveryTriagePresentation::RECOVERY_EVIDENCE_WEAKENED],
                'triage_sort' => TenantRecoveryTriagePresentation::TRIAGE_SORT_WORST_FIRST,
            ],
        ]),
    ], (int) $tenant->workspace_id);

    DB::flushQueryLog();
    DB::enableQueryLog();

    $resolver = app(PortfolioArrivalContextResolver::class);

    $resolver->resolve($request, $tenant);
    $firstQueryCount = count(DB::getQueryLog());

    $resolver->resolve($request, $tenant);
    $secondQueryCount = count(DB::getQueryLog());

    expect($firstQueryCount)->toBeGreaterThan(0)
        ->and($secondQueryCount)->toBe($firstQueryCount);
});

it('renders the arrival continuity shell and productized overview DB-only with bounded query volume', function (): void {
    [$user, $tenant] = $this->makePortfolioTriageActor('DB Only Arrival ManagedEnvironment');
    $this->seedPortfolioRecoveryConcern($tenant, RestoreResultAttention::STATE_PARTIAL);
    $this->actingAs($user);

    $arrivalUrl = EnvironmentDashboard::getUrl([
        PortfolioArrivalContextToken::QUERY_PARAMETER => PortfolioArrivalContextToken::encode([
            'sourceSurface' => PortfolioArrivalContextToken::SOURCE_WORKSPACE_OVERVIEW,
            'tenantRouteKey' => (string) $tenant->external_id,
            'workspaceId' => (int) $tenant->workspace_id,
            'concernFamily' => PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE,
            'concernState' => TenantRecoveryTriagePresentation::RECOVERY_EVIDENCE_WEAKENED,
            'concernReason' => RestoreResultAttention::STATE_PARTIAL,
        ]),
    ], panel: 'admin', tenant: $tenant);

    DB::flushQueryLog();
    DB::enableQueryLog();

    assertNoOutboundHttp(function () use ($arrivalUrl): void {
        $this->get($arrivalUrl)
            ->assertOk()
            ->assertSee('Triage arrival')
            ->assertSee('Open restore run');
    });

    expect(count(DB::getQueryLog()))->toBeLessThanOrEqual(190);
});
