<?php

use App\Livewire\BulkOperationProgress;
use App\Models\OperationRun;
use Filament\Facades\Filament;
use Illuminate\Support\Collection;
use Livewire\Livewire;

test('progress widget shows only queued and running operation runs', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $otherUser = \App\Models\User::factory()->create();
    createUserWithTenant(tenant: $tenant, user: $otherUser, role: 'owner');

    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'status' => 'queued',
        'outcome' => 'pending',
    ]);

    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $otherUser->id,
        'status' => 'running',
        'outcome' => 'pending',
    ]);

    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'status' => 'completed',
        'outcome' => 'succeeded',
    ]);

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

    $runs = $component->get('runs');
    expect($runs)->toBeInstanceOf(Collection::class);
    expect($runs)->toHaveCount(2);
    expect($runs->pluck('status')->unique()->values()->all())->toEqualCanonicalizing(['queued', 'running']);
    expect($runs->pluck('user_id')->all())->toContain($otherUser->id);
})->group('ops-ux');

it('keeps stale backup set update runs visible in the progress widget', function (string $operationType): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'workspace_id' => $tenant->workspace_id,
        'user_id' => $user->id,
        'type' => $operationType,
        'status' => 'queued',
        'outcome' => 'pending',
        'started_at' => null,
        'created_at' => now()->subMinutes(20),
    ]);

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

    expect($component->get('runs'))->toBeInstanceOf(Collection::class)
        ->and($component->get('runs'))->toHaveCount(1)
        ->and($component->get('runs')->first()->freshnessState()->value)->toBe('likely_stale')
        ->and($component->get('hasActiveRuns'))->toBeTrue();
})->with([
    'backup set update' => 'backup_set.update',
])->group('ops-ux');
