<?php

declare(strict_types=1);

use App\Filament\Pages\InventoryCoverage;
use App\Filament\Resources\InventoryItemResource;
use App\Models\InventoryItem;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Support\OperationRunLinks;
use App\Support\OperationRunOutcome;
use App\Support\Workspaces\WorkspaceContext;

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

function seedSpec177InventoryCoverageTruthFixtures(ManagedEnvironment $tenant): OperationRun
{
    foreach (range(1, 130) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Browser Inventory %02d', $index),
            'policy_type' => 'deviceConfiguration',
            'external_id' => sprintf('browser-inventory-%02d', $index),
            'platform' => 'windows',
            'last_seen_at' => now()->subMinutes($index),
        ]);
    }

    InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'display_name' => 'Browser Conditional Access',
        'policy_type' => 'conditionalAccessPolicy',
        'external_id' => 'browser-conditional-access',
        'platform' => 'windows',
        'last_seen_at' => now()->subMinutes(31),
    ]);

    return createInventorySyncOperationRunWithCoverage(
        $tenant,
        [
            'conditionalAccessPolicy' => 'succeeded',
            'deviceConfiguration' => 'failed',
            'roleScopeTag' => 'skipped',
        ],
        ['roleScopeTag'],
        [
            'outcome' => OperationRunOutcome::PartiallySucceeded->value,
            'completed_at' => now()->subMinute(),
        ],
    );
}

function seedSpec177InventoryItemFilterPaginationFixtures(ManagedEnvironment $tenant): void
{
    foreach (range(1, 45) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Windows Fresh Device %02d', $index),
            'policy_type' => 'deviceConfiguration',
            'external_id' => sprintf('windows-fresh-device-%02d', $index),
            'platform' => 'windows',
            'last_seen_at' => now()->subMinutes($index),
        ]);
    }

    foreach (range(1, 3) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Mac Fresh Device %02d', $index),
            'policy_type' => 'deviceConfiguration',
            'external_id' => sprintf('mac-fresh-device-%02d', $index),
            'platform' => 'macOS',
            'last_seen_at' => now()->subMinutes(45 + $index),
        ]);
    }

    foreach (range(1, 3) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Conditional Access Fresh %02d', $index),
            'policy_type' => 'conditionalAccessPolicy',
            'external_id' => sprintf('conditional-access-fresh-%02d', $index),
            'platform' => 'windows',
            'last_seen_at' => now()->subMinutes(48 + $index),
        ]);
    }

    foreach (range(46, 55) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Windows Fresh Device %02d', $index),
            'policy_type' => 'deviceConfiguration',
            'external_id' => sprintf('windows-fresh-device-%02d', $index),
            'platform' => 'windows',
            'last_seen_at' => now()->subMinutes(6 + $index),
        ]);
    }

    foreach (range(1, 3) as $index) {
        InventoryItem::factory()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'display_name' => sprintf('Windows Stale Device %02d', $index),
            'policy_type' => 'deviceConfiguration',
            'external_id' => sprintf('windows-stale-device-%02d', $index),
            'platform' => 'windows',
            'last_seen_at' => now()->subDays(3)->subMinutes($index),
        ]);
    }
}

it('smokes inventory coverage truth surfaces with filters, pagination, and run drill-through', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Spec177 Browser ManagedEnvironment',
        'external_id' => 'spec177-browser-tenant',
    ]);

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

    $run = seedSpec177InventoryCoverageTruthFixtures($tenant);

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

        $coverageUrl = InventoryCoverage::getUrl(panel: 'admin', tenant: $tenant);
    $basisRunUrl = OperationRunLinks::view($run, $tenant);
        $inventoryItemsUrl = InventoryItemResource::getUrl('index', panel: 'admin', tenant: $tenant);

    $searchPage = visit(InventoryItemResource::getUrl('index', panel: 'admin', tenant: $tenant));

    $searchPage
        ->waitForText('Inventory Items')
        ->assertNoJavaScriptErrors()
        ->assertSee('Covered types')
        ->assertSee('Need follow-up')
        ->assertSee('Coverage basis')
        ->assertSee('Open basis run')
        ->assertSee('Browser Inventory 01')
        ->assertDontSee('Browser Inventory 130')
        ->fill('main input[placeholder="Search"]', 'Browser Inventory 01')
        ->waitForText('Browser Inventory 01')
        ->assertNoJavaScriptErrors()
        ->assertSee('Browser Inventory 01')
        ->assertDontSee('Browser Inventory 02');

    $page = visit($coverageUrl);

    $page
        ->waitForText('ManagedEnvironment coverage truth')
        ->assertNoJavaScriptErrors()
        ->assertSee('Latest coverage-bearing sync completed')
        ->assertSee('Open basis run')
        ->assertSee('Open inventory items')
        ->fill('input[placeholder="Search by type or label"]', 'Conditional Access')
        ->waitForText('Conditional Access')
        ->assertNoJavaScriptErrors()
        ->assertSee('Conditional Access')
        ->assertScript("document.querySelector('input[placeholder=\"Search by type or label\"]')?.value === 'Conditional Access'", true)
        ->assertScript("Array.from(document.querySelectorAll('a[href=\"{$basisRunUrl}\"]')).some((element) => element.textContent?.includes('Open basis run'))", true);

    visit($basisRunUrl)
        ->waitForText('Operation #'.(int) $run->getKey())
        ->assertNoJavaScriptErrors()
        ->assertRoute('admin.operations.view', [
            'workspace' => (int) $run->workspace_id,
            'run' => (int) $run->getKey(),
        ])
        ->assertSee('Inventory sync coverage')
        ->assertSee('Need follow-up');

    visit($coverageUrl)
        ->waitForText('ManagedEnvironment coverage truth')
        ->assertNoJavaScriptErrors()
        ->assertScript("Array.from(document.querySelectorAll('a[href=\"{$inventoryItemsUrl}\"]')).some((element) => element.textContent?.includes('Open inventory items'))", true);

    visit($inventoryItemsUrl)
        ->waitForText('Inventory Items')
        ->assertNoJavaScriptErrors()
        ->assertSee('Browser Inventory 01');
});

it('smokes inventory item pagination with stable browser slices', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Spec177 Browser Filter ManagedEnvironment',
        'external_id' => 'spec177-browser-filter-tenant',
    ]);

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

    seedSpec177InventoryItemFilterPaginationFixtures($tenant);

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

    $page = visit(InventoryItemResource::getUrl('index', tenant: $tenant));

    $page
        ->waitForText('Inventory Items')
        ->assertNoJavaScriptErrors()
        ->assertSee('Windows Fresh Device 01')
        ->assertDontSee('Windows Fresh Device 30')
        ->assertDontSee('Mac Fresh Device 01')
        ->wait(1);

    $page->click('[aria-label="Go to page 2"]');

    $page
        ->wait(1)
        ->waitForText('Mac Fresh Device 01')
        ->assertNoJavaScriptErrors()
        ->assertSee('Mac Fresh Device 01')
        ->assertSee('Conditional Access Fresh 01')
        ->assertDontSee('Windows Fresh Device 46')
        ->assertDontSee('Windows Fresh Device 01');

    $page->click('[aria-label="Go to page 3"]');

    $page
        ->wait(1)
        ->waitForText('Windows Fresh Device 46')
        ->assertNoJavaScriptErrors()
        ->assertSee('Windows Fresh Device 46')
        ->waitForText('Windows Fresh Device 51')
        ->assertSee('Windows Fresh Device 51')
        ->assertSee('Windows Stale Device 01')
        ->assertDontSee('Mac Fresh Device 01');
});
