<?php

declare(strict_types=1);

use App\Filament\Resources\EntraGroupResource;
use App\Models\EntraGroup;
use App\Models\ManagedEnvironment;
use App\Support\ManagedEnvironmentLinks;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

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

it('smokes environment-bound directory groups navigation and view drilldown', function (): void {
    [$user, $environment] = createUserWithTenant(
        role: 'owner',
        workspaceRole: 'manager',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    $environment->forceFill([
        'name' => 'Spec 303 Production',
        'slug' => 'spec-303-production',
        'kind' => 'production',
        'lifecycle_status' => ManagedEnvironment::STATUS_ACTIVE,
    ])->save();

    $group = EntraGroup::factory()->for($environment)->create([
        'display_name' => 'Spec 303 Browser Directory Group',
        'last_seen_at' => now(),
    ]);
    $groupsUrl = EntraGroupResource::getUrl(
        panel: 'admin',
        tenant: $environment,
    );
    $groupsPath = (string) parse_url($groupsUrl, PHP_URL_PATH);
    $groupViewPath = (string) parse_url(
        EntraGroupResource::getUrl(
            'view',
            ['record' => $group],
            panel: 'admin',
            tenant: $environment,
        ),
        PHP_URL_PATH,
    );

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

    visit(route('admin.workspace.home', ['workspace' => $environment->workspace]))
        ->waitForText('Overview')
        ->assertScript("Array.from(document.querySelectorAll('a')).every((link) => link.pathname !== '{$groupsPath}')", true)
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    $environmentPage = visit(ManagedEnvironmentLinks::viewUrl($environment))
        ->waitForText('Spec 303 Production')
        ->assertNoJavaScriptErrors();

    $environmentPage
        ->assertScript("Array.from(document.querySelectorAll('a')).some((link) => link.pathname === '{$groupsPath}' && link.textContent?.includes('Groups'))", true)
        ->assertScript("Array.from(document.querySelectorAll('a')).filter((link) => link.pathname === '{$groupsPath}' && link.textContent?.includes('Groups')).length === 1", true)
        ->click("a[href$=\"{$groupsPath}\"]")
        ->waitForText('Spec 303 Browser Directory Group')
        ->assertScript("window.location.pathname === '{$groupsPath}'", true)
        ->assertScript("! window.location.pathname.includes('/admin/t/')", true)
        ->click('tbody tr.fi-ta-row:first-of-type')
        ->waitForText('Spec 303 Browser Directory Group')
        ->assertScript("window.location.pathname === '{$groupViewPath}'", true)
        ->assertScript("! window.location.pathname.includes('/admin/t/')", true)
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();
});
