<?php

declare(strict_types=1);

use App\Filament\Pages\InventoryCoverage;
use App\Filament\Resources\InventoryItemResource;
use App\Models\ManagedEnvironment;
use App\Support\ManagedEnvironmentLinks;
use App\Support\Workspaces\WorkspaceContext;

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

it('smokes inventory navigation cutover between workspace and environment surfaces', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Spec301 Inventory Navigation',
        'external_id' => 'spec301-inventory-navigation',
    ]);

    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

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

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

    $workspaceHomeUrl = route('admin.workspace.home', ['workspace' => (int) $tenant->workspace_id]);
    $environmentUrl = ManagedEnvironmentLinks::viewUrl($tenant);
    $inventoryItemsUrl = InventoryItemResource::getUrl('index', panel: 'admin', tenant: $tenant);
    $coverageUrl = InventoryCoverage::getUrl(panel: 'admin', tenant: $tenant);
    $inventoryClusterPathPattern = '\\/admin\\/workspaces\\/[^\\/]+\\/environments\\/[^\\/]+\\/inventory$';
    $coveragePath = (string) parse_url($coverageUrl, PHP_URL_PATH);

    visit($workspaceHomeUrl)
        ->waitForText('Overview')
        ->assertNoJavaScriptErrors()
        ->assertScript("Array.from(document.querySelectorAll('a')).every((link) => ! new RegExp('{$inventoryClusterPathPattern}').test(link.pathname))", true)
        ->assertScript("Array.from(document.querySelectorAll('a')).every((link) => link.pathname !== '{$coveragePath}')", true);

    visit($environmentUrl)
        ->waitForText('Spec301 Inventory Navigation')
        ->assertNoJavaScriptErrors()
        ->assertScript("Array.from(document.querySelectorAll('a')).some((link) => new RegExp('{$inventoryClusterPathPattern}').test(link.pathname))", true);

    visit($inventoryItemsUrl)
        ->waitForText('Inventory Items')
        ->assertNoJavaScriptErrors()
        ->assertScript("document.querySelector('a[href=\"{$coverageUrl}\"]') !== null", true)
        ->click('Coverage')
        ->waitForText('ManagedEnvironment coverage truth')
        ->assertNoJavaScriptErrors()
        ->assertScript("window.location.pathname === '{$coveragePath}'", true);
});
