<?php

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

uses(RefreshDatabase::class);

test('backup sets table bulk restore restores archived sets and their items', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

    Filament::setTenant($tenant, true);

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

    $item = BackupItem::create([
        'tenant_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_restore', collect([$set]))
        ->assertHasNoTableBulkActionErrors();

    $set->refresh();
    $item->refresh();

    expect($set->trashed())->toBeFalse();
    expect($item->trashed())->toBeFalse();

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

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