<?php

use App\Filament\Resources\PolicyResource\Pages\ViewPolicy;
use App\Jobs\CapturePolicySnapshotJob;
use App\Models\OperationRun;
use App\Models\Policy;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('reuses an active run on double click (idempotency)', function () {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'owner');
    $this->actingAs($user);

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

    $policy = Policy::factory()->for($tenant)->create();

    Livewire::test(ViewPolicy::class, ['record' => $policy->getRouteKey()])
        ->callAction('capture_snapshot', data: [
            'include_assignments' => true,
            'include_scope_tags' => true,
        ]);

    Livewire::test(ViewPolicy::class, ['record' => $policy->getRouteKey()])
        ->callAction('capture_snapshot', data: [
            'include_assignments' => true,
            'include_scope_tags' => true,
        ]);

    expect(OperationRun::query()
        ->where('managed_environment_id', $tenant->id)
        ->where('type', 'policy.capture_snapshot')
        ->count())->toBe(1);

    Queue::assertPushed(CapturePolicySnapshotJob::class, 1);
});
