<?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\Monitoring\FindingExceptionsQueue;
use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Filament\Pages\Reviews\ReviewRegister;
use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ManagedEnvironment;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;

pest()->browser()->timeout(30_000);

it('Spec314 smokes clean workspace hub navigation context', function (): void {
    $environment = ManagedEnvironment::factory()->active()->create([
        'name' => 'Spec314 Browser Environment',
    ]);
    [$user, $environment] = createUserWithTenant(tenant: $environment, role: 'owner');
    $workspace = $environment->workspace()->firstOrFail();

    $this->actingAs($user)->withSession([
        WorkspaceContext::SESSION_KEY => (int) $workspace->getKey(),
        WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY => [
            (string) $workspace->getKey() => (int) $environment->getKey(),
        ],
    ]);

    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
    session()->put(WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY, [
        (string) $workspace->getKey() => (int) $environment->getKey(),
    ]);

    $hubUrls = [
        ProviderConnectionResource::getUrl('index', panel: 'admin'),
        FindingExceptionsQueue::getUrl(panel: 'admin'),
        OperationRunLinks::index(),
        DecisionRegister::getUrl(panel: 'admin'),
        CustomerReviewWorkspace::getUrl(panel: 'admin'),
        route('admin.evidence.overview'),
        ReviewRegister::getUrl(panel: 'admin'),
        GovernanceInbox::getUrl(panel: 'admin'),
    ];

    $assertCleanWorkspaceHub = function (mixed $page, string $url): void {
        $expectedPath = json_encode((string) parse_url($url, PHP_URL_PATH), JSON_THROW_ON_ERROR);

        $page
            ->assertSee(__('localization.shell.no_environment_selected'))
            ->assertDontSee(__('localization.shell.environment_scope').': Spec314 Browser Environment')
            ->assertScript("window.location.pathname === {$expectedPath}", true)
            ->assertScript('! window.location.search.includes("tenant=")', true)
            ->assertScript('! window.location.search.includes("tenant_id=")', true)
            ->assertScript('! window.location.search.includes("managed_environment_id=")', true)
            ->assertScript('! window.location.search.includes("environment_id=")', true)
            ->assertScript('! window.location.search.includes("tenant_scope=")', true)
            ->assertScript('! window.location.search.includes("tableFilters")', true)
            ->assertNoJavaScriptErrors()
            ->assertNoConsoleLogs();
    };

    visit(EnvironmentDashboard::getUrl(panel: 'admin', tenant: $environment))
        ->assertSee('Spec314 Browser Environment')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    foreach ($hubUrls as $url) {
        $page = visit($url);

        $assertCleanWorkspaceHub($page, $url);

        $page->script('window.location.reload();');

        $page->waitForText(__('localization.shell.no_environment_selected'));
        $assertCleanWorkspaceHub($page, $url);
    }

    visit(route('admin.workspace.home', ['workspace' => $workspace]))
        ->waitForText('Workspace overview')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    foreach ($hubUrls as $url) {
        $page = visit($url);

        $assertCleanWorkspaceHub($page, $url);
    }

    $historyPage = visit($hubUrls[0]);
    $assertCleanWorkspaceHub($historyPage, $hubUrls[0]);

    foreach (array_slice($hubUrls, 1, 4) as $url) {
        $encodedUrl = json_encode($url, JSON_THROW_ON_ERROR);

        $historyPage->script("window.location.assign({$encodedUrl});");
        $historyPage->waitForText(__('localization.shell.no_environment_selected'));
        $assertCleanWorkspaceHub($historyPage, $url);
    }

    $historyPage->script('window.history.back();');
    $historyPage->waitForText(__('localization.shell.no_environment_selected'));
    $assertCleanWorkspaceHub($historyPage, $hubUrls[3]);

    $historyPage->script('window.history.forward();');
    $historyPage->waitForText(__('localization.shell.no_environment_selected'));
    $assertCleanWorkspaceHub($historyPage, $hubUrls[4]);
});
