<?php

declare(strict_types=1);

use App\Filament\Resources\InventoryItemResource\Pages\ListInventoryItems;
use App\Models\InventoryItem;
use App\Models\ManagedEnvironment;
use Filament\Facades\Filament;
use Livewire\Livewire;

it('filters inventory items by policy type, platform, and freshness inside the active tenant', function (): void {
    $tenantA = ManagedEnvironment::factory()->create();
    [$user, $tenantA] = createUserWithTenant(tenant: $tenantA, role: 'owner');

    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => (int) $tenantA->workspace_id,
    ]);

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'owner');

    $matching = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'last_seen_at' => now(),
    ]);

    $stale = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenantA->getKey(),
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'last_seen_at' => now()->subDays(3),
    ]);

    $otherTenant = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows',
        'last_seen_at' => now(),
    ]);

    $this->actingAs($user);
    $tenantA->makeCurrent();
    Filament::setTenant($tenantA, true);

    Livewire::test(ListInventoryItems::class)
        ->filterTable('policy_type', 'deviceConfiguration')
        ->filterTable('platform', 'windows')
        ->filterTable('stale', '0')
        ->assertCanSeeTableRecords([$matching])
        ->assertCanNotSeeTableRecords([$stale, $otherTenant]);
});

it('clears inventory item filters back to the tenant-scoped list', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $fresh = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'platform' => 'windows',
        'last_seen_at' => now(),
    ]);

    $stale = InventoryItem::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'platform' => 'windows',
        'last_seen_at' => now()->subDays(3),
    ]);

    $this->actingAs($user);
    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    $component = Livewire::test(ListInventoryItems::class)
        ->filterTable('platform', 'windows')
        ->filterTable('stale', '1')
        ->assertCanSeeTableRecords([$stale])
        ->assertCanNotSeeTableRecords([$fresh]);

    $component
        ->set('tableFilters.platform.value', null)
        ->set('tableFilters.stale.value', null)
        ->assertCanSeeTableRecords([$fresh, $stale]);
});
