<?php

use App\Livewire\BulkOperationProgress;
use App\Models\OperationRun;
use App\Support\OpsUx\OperationRunUrl;
use Filament\Facades\Filament;
use Livewire\Livewire;

test('progress widget limits visible active runs to three and exposes overflow count', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    OperationRun::factory()->count(2)->create([
        'managed_environment_id' => $tenant->id,
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'inventory_sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'created_at' => now(),
    ]);

    OperationRun::factory()->count(2)->create([
        'managed_environment_id' => $tenant->id,
        'workspace_id' => (int) $tenant->workspace_id,
        'type' => 'inventory_sync',
        'status' => 'queued',
        'outcome' => 'pending',
        'created_at' => now()->subHour(),
    ]);

    $component = Livewire::actingAs($user)
        ->test(BulkOperationProgress::class)
        ->call('refreshRuns');

    $html = html_entity_decode($component->html(), ENT_QUOTES | ENT_HTML5);
    $pageText = preg_replace('/\s+/', ' ', strip_tags($html));

    expect($component->get('runs'))->toHaveCount(3);
    expect($component->get('overflowCount'))->toBe(1);
    expect($component->get('runs')->map(fn (OperationRun $run): string => $run->freshnessState()->value)->unique()->values()->all())
        ->toEqualCanonicalizing(['fresh_active', 'likely_stale']);
    expect($html)->toContain('Review operations')
        ->and($html)->not->toContain('View operation')
        ->and($html)->toContain('data-testid="ops-ux-activity-feedback-overflow-link"')
        ->and($html)->toContain(OperationRunUrl::index($tenant));
    expect($pageText)->toContain('1 more operation update available in Operations.');
})->group('ops-ux');
