<?php

use App\Livewire\BulkOperationProgress;
use App\Models\OperationRun;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('progress widget shows running operations for current tenant and user', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

    // Active op
    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'initiator_name' => $user->name,
        'type' => 'policy.delete',
        'status' => 'running',
        'outcome' => 'pending',
        'context' => ['scope' => 'subset'],
    ]);

    // Completed op (should not show)
    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'initiator_name' => $user->name,
        'type' => 'policy.delete',
        'status' => 'completed',
        'outcome' => 'succeeded',
        'updated_at' => now()->subMinutes(5),
    ]);

    Livewire::actingAs($user)
        ->test(BulkOperationProgress::class)
        ->assertSee('Delete policies')
        ->assertDontSee('Unknown operation');
});

test('progress widget shows queued backup schedule runs as operation runs', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);
    setAdminPanelContext($tenant);

    OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'initiator_name' => $user->name,
        'type' => 'backup_schedule_run',
        'status' => 'queued',
        'outcome' => 'pending',
        'context' => ['scope' => 'scheduled'],
        'created_at' => now()->subMinutes(2),
        'updated_at' => now()->subMinutes(2),
    ]);

    Livewire::actingAs($user)
        ->test(BulkOperationProgress::class)
        ->assertSee('Backup schedule run');
});
