<?php

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

uses(RefreshDatabase::class);

it('queues a capture snapshot job (no inline Graph capture)', function () {
    Queue::fake();

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

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

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

    $this->mock(VersionService::class, function (MockInterface $mock) {
        $mock->shouldReceive('captureFromGraph')->never();
    });

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

    Queue::assertPushed(CapturePolicySnapshotJob::class);

    $run = OperationRun::query()
        ->where('managed_environment_id', $tenant->id)
        ->where('type', 'policy.capture_snapshot')
        ->latest('id')
        ->first();

    expect($run)->not->toBeNull();
    expect($run->context['policy_id'] ?? null)->toBe((int) $policy->getKey());
});
