<?php

use App\Filament\Resources\BackupSetResource\Pages\EditBackupSet;
use App\Filament\Resources\BackupSetResource\RelationManagers\BackupItemsRelationManager;
use App\Jobs\RemovePoliciesFromBackupSetJob;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\OperationRun;
use App\Services\Graph\GraphClientInterface;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

it('queues a canonical operation run for row remove and does not call Graph during the 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);

    $backupSet = BackupSet::factory()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Test backup',
    ]);

    $backupItem = BackupItem::factory()->for($backupSet)->for($tenant)->create();

    Livewire::test(BackupItemsRelationManager::class, [
        'ownerRecord' => $backupSet,
        'pageClass' => EditBackupSet::class,
    ])
        ->callTableAction('remove', $backupItem);

    Queue::assertPushed(RemovePoliciesFromBackupSetJob::class, function (RemovePoliciesFromBackupSetJob $job) use ($backupSet, $backupItem, $user) {
        return $job->backupSetId === (int) $backupSet->getKey()
            && $job->backupItemIds === [(int) $backupItem->getKey()]
            && $job->initiatorUserId === (int) $user->getKey();
    });

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

    expect($run)->not->toBeNull();
    expect($run->status)->toBe('queued');
    expect($run->context['backup_set_id'] ?? null)->toBe((int) $backupSet->getKey());
});
