<?php

use App\Filament\Pages\InventoryLanding;
use App\Jobs\RunInventorySyncJob;
use App\Models\OperationRun;
use App\Services\Graph\GraphClientInterface;
use App\Services\Inventory\InventorySyncService;
use App\Support\OperationRunLinks;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

it('enqueues inventory sync and creates a canonical operation run without calling Graph in request', function () {
    Queue::fake();

    $this->mock(GraphClientInterface::class, function ($mock): void {
        $mock->shouldReceive('listPolicies')->never();
        $mock->shouldReceive('getPolicy')->never();
        $mock->shouldReceive('getOrganization')->never();
        $mock->shouldReceive('applyPolicy')->never();
        $mock->shouldReceive('getServicePrincipalPermissions')->never();
        $mock->shouldReceive('request')->never();
    });

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

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

    $sync = app(InventorySyncService::class);
    $policyTypes = $sync->defaultSelectionPayload()['policy_types'] ?? [];

    Livewire::test(InventoryLanding::class)
        ->callAction('run_inventory_sync', data: ['policy_types' => $policyTypes]);

    $opRun = OperationRun::query()
        ->where('tenant_id', $tenant->getKey())
        ->where('type', 'inventory.sync')
        ->latest('id')
        ->first();

    expect($opRun)->not->toBeNull();
    expect($opRun?->status)->toBe('queued');
    expect($opRun?->outcome)->toBe('pending');

    $notifications = session('filament.notifications', []);
    expect($notifications)->not->toBeEmpty();
    expect(collect($notifications)->last()['actions'][0]['url'] ?? null)
        ->toBe(OperationRunLinks::view($opRun, $tenant));

    Queue::assertPushed(RunInventorySyncJob::class, function (RunInventorySyncJob $job) use ($tenant, $user, $opRun): bool {
        return $job->tenantId === (int) $tenant->getKey()
            && $job->userId === (int) $user->getKey()
            && $job->operationRun instanceof OperationRun
            && (int) $job->operationRun->getKey() === (int) $opRun?->getKey();
    });
});
