<?php

declare(strict_types=1);

use App\Filament\Widgets\Inventory\InventoryKpiHeader;
use App\Livewire\BulkOperationProgress;
use App\Models\OperationRun;
use Filament\Facades\Filament;
use Filament\Widgets\StatsOverviewWidget\Stat;
use App\Support\OpsUx\OpsUxBrowserEvents;
use Livewire\Livewire;

function inventoryKpiValues($component): array
{
    $method = new \ReflectionMethod(InventoryKpiHeader::class, 'getStats');
    $method->setAccessible(true);

    return collect($method->invoke($component->instance()))
        ->mapWithKeys(fn (Stat $stat): array => [
            (string) $stat->getLabel() => (string) $stat->getValue(),
        ])
        ->all();
}

it('keeps the inventory active ops KPI aligned with the shell activity banner for the same tenant', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'inventory_sync',
        'status' => 'running',
        'outcome' => 'pending',
        'started_at' => now()->subMinute(),
    ]);

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

    $banner = Livewire::test(BulkOperationProgress::class)
        ->call('refreshRuns');

    $kpis = inventoryKpiValues(Livewire::test(InventoryKpiHeader::class));

    expect($banner->get('hasActiveRuns'))->toBeTrue()
        ->and($banner->get('runs'))->toHaveCount(1)
        ->and($kpis)->toMatchArray([
            'Active ops' => '1',
        ]);
});

it('refreshes the inventory active ops KPI and shell banner together after a run is enqueued', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

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

    $banner = Livewire::test(BulkOperationProgress::class);
    $kpi = Livewire::test(InventoryKpiHeader::class);

    expect($banner->get('hasActiveRuns'))->toBeFalse()
        ->and(inventoryKpiValues($kpi))->toMatchArray([
            'Active ops' => '0',
        ]);

    OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $user->getKey(),
        'type' => 'inventory_sync',
        'status' => 'running',
        'outcome' => 'pending',
        'started_at' => now()->subMinute(),
    ]);

    $banner->dispatch(OpsUxBrowserEvents::RunEnqueued, tenantId: (int) $tenant->getKey());
    $kpi->dispatch(OpsUxBrowserEvents::RunEnqueued, tenantId: (int) $tenant->getKey());

    expect($banner->get('hasActiveRuns'))->toBeTrue()
        ->and($banner->get('runs'))->toHaveCount(1)
        ->and(inventoryKpiValues($kpi))->toMatchArray([
            'Active ops' => '1',
        ]);
});