<?php

use App\Filament\Resources\BackupSetResource;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\OperationRun;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('backup sets table bulk force delete permanently deletes archived sets and their items', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');
    setAdminPanelContext($tenant);

    $set = BackupSet::create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Backup',
        'status' => 'completed',
        'item_count' => 1,
    ]);

    $item = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $set->id,
        'policy_id' => null,
        'policy_identifier' => 'policy-1',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows10',
        'payload' => ['id' => 'policy-1'],
        'metadata' => null,
    ]);

    $set->delete();

    Livewire::actingAs($user)
        ->test(BackupSetResource\Pages\ListBackupSets::class)
        ->filterTable(\Filament\Tables\Filters\TrashedFilter::class, false)
        ->callTableBulkAction('bulk_force_delete', collect([$set]))
        ->assertHasNoTableBulkActionErrors();

    expect(BackupSet::withTrashed()->find($set->id))->toBeNull();
    expect(BackupItem::withTrashed()->find($item->id))->toBeNull();

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

    expect($opRun)->not->toBeNull();
    expect($opRun->status)->toBe('completed');
});
