<?php

declare(strict_types=1);

use App\Filament\Pages\EnvironmentDashboard;
use App\Filament\Resources\ProviderConnectionResource;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Support\ManagedEnvironmentLinks;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

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

it('smokes Spec 300 managed-environment naming consolidation proof surfaces', function (): void {
    [$user, $environment] = createUserWithTenant(
        role: 'owner',
        workspaceRole: 'owner',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    $environment->forceFill([
        'name' => 'Spec 300 Production',
        'slug' => 'spec-300-production',
        'managed_environment_id' => '30000000-0000-0000-0000-000000000300',
    ])->save();

    $workspace = $environment->workspace()->firstOrFail();

    $connection = ProviderConnection::factory()->platform()->consentGranted()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => (int) $environment->getKey(),
        'display_name' => 'Spec 300 Microsoft Connection',
        'entra_tenant_id' => '30000000-0000-0000-0000-000000000300',
        'is_default' => true,
        'verification_status' => 'healthy',
    ]);

    OperationRun::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'managed_environment_id' => (int) $environment->getKey(),
        'type' => 'inventory_sync',
        'status' => OperationRunStatus::Queued->value,
        'outcome' => OperationRunOutcome::Pending->value,
    ]);

    $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());

    $workspaceOverviewPath = (string) parse_url(route('admin.workspace.home', ['workspace' => $workspace]), PHP_URL_PATH);
    $environmentIndexPath = (string) parse_url(ManagedEnvironmentLinks::indexUrl($workspace), PHP_URL_PATH);
    $environmentDashboardPath = (string) parse_url(EnvironmentDashboard::getUrl(tenant: $environment), PHP_URL_PATH);
    $operationsPath = (string) parse_url(ManagedEnvironmentLinks::operationsUrl($environment), PHP_URL_PATH);
    $providerConnectionPath = (string) parse_url(
        ProviderConnectionResource::getUrl('view', [
            'record' => $connection,
            'managed_environment_id' => $environment->external_id,
        ], panel: 'admin'),
        PHP_URL_PATH,
    );
    $requiredPermissionsPath = (string) parse_url(ManagedEnvironmentLinks::requiredPermissionsUrl($environment), PHP_URL_PATH);

    visit(route('admin.workspace.home', ['workspace' => $workspace]))
        ->waitForText('Workspace overview')
        ->assertScript("window.location.pathname === '{$workspaceOverviewPath}'", true)
        ->assertSee('Accessible environments')
        ->assertDontSee('Accessible tenants')
        ->assertDontSee('/admin/t/')
        ->assertDontSee('/admin/tenants')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    $dashboard = visit(ManagedEnvironmentLinks::indexUrl($workspace))
        ->waitForText('Spec 300 Production')
        ->assertScript("window.location.pathname === '{$environmentIndexPath}'", true)
        ->assertDontSee('/admin/t/')
        ->assertDontSee('/admin/tenants')
        ->click('[wire\\:key="tenant-'.$environment->getKey().'"]')
        ->waitForText('Spec 300 Production')
        ->waitForText('Show all operations')
        ->assertScript("window.location.pathname === '{$environmentDashboardPath}'", true)
        ->assertDontSee('Tenant dashboard')
        ->assertDontSee('Tenant required permissions')
        ->assertDontSee('/admin/t/')
        ->assertDontSee('/admin/tenants')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    $dashboard
        ->assertSee('Operations')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    visit(ManagedEnvironmentLinks::operationsUrl($environment))
        ->waitForText('Monitoring landing')
        ->assertSee('Spec 300 Production')
        ->assertScript("window.location.pathname === '{$operationsPath}'", true)
        ->assertScript("window.location.search.includes('environment_id={$environment->getKey()}')", true)
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    visit(ProviderConnectionResource::getUrl('view', [
        'record' => $connection,
        'environment_id' => (int) $environment->getKey(),
    ], panel: 'admin'))
        ->waitForText('Spec 300 Microsoft Connection')
        ->assertScript("window.location.pathname === '{$providerConnectionPath}'", true)
        ->assertSee('Microsoft tenant ID')
        ->assertSee('Spec 300 Production')
        ->assertDontSee('/admin/t/')
        ->assertDontSee('/admin/tenants')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();

    visit(ManagedEnvironmentLinks::requiredPermissionsUrl($environment))
        ->waitForText('Required permissions')
        ->assertScript("window.location.pathname === '{$requiredPermissionsPath}'", true)
        ->assertSee('Missing')
        ->assertDontSee('Tenant required permissions')
        ->assertDontSee('/admin/t/')
        ->assertDontSee('/admin/tenants')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();
});
