<?php

use App\Jobs\AddPoliciesToBackupSetJob;
use App\Livewire\BackupSetPolicyPickerTable;
use App\Models\BackupSet;
use App\Models\OperationRun;
use App\Models\Policy;
use App\Services\Graph\GraphClientInterface;
use App\Support\OperationRunLinks;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

it('enqueues backup set add-policies via canonical operation run (no Graph calls 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);

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

    $policies = Policy::factory()->count(2)->create([
        'managed_environment_id' => $tenant->id,
        'ignored_at' => null,
        'last_synced_at' => now(),
    ]);

    Livewire::actingAs($user)
        ->test(BackupSetPolicyPickerTable::class, [
            'backupSetId' => $backupSet->id,
        ])
        ->callTableBulkAction('add_selected_to_backup_set', $policies)
        ->assertHasNoTableBulkActionErrors();

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

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

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

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