<?php

use App\Filament\Resources\RestoreRunResource;
use App\Models\BackupSet;
use App\Models\BulkOperationRun;
use App\Models\RestoreRun;
use App\Models\Tenant;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

test('bulk delete restore runs skips running items', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();
    $user->tenants()->syncWithoutDetaching([
        $tenant->getKey() => ['role' => 'owner'],
    ]);

    Filament::setTenant($tenant, true);

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

    $completedRuns = collect(range(1, 3))->map(function () use ($tenant, $backupSet) {
        return RestoreRun::create([
            'tenant_id' => $tenant->id,
            'backup_set_id' => $backupSet->id,
            'status' => 'completed',
            'is_dry_run' => true,
            'requested_by' => 'tester@example.com',
        ]);
    });

    $running = RestoreRun::create([
        'tenant_id' => $tenant->id,
        'backup_set_id' => $backupSet->id,
        'status' => 'running',
        'is_dry_run' => true,
        'requested_by' => 'tester@example.com',
    ]);

    $records = $completedRuns->concat([$running]);

    Livewire::actingAs($user)
        ->test(RestoreRunResource\Pages\ListRestoreRuns::class)
        ->callTableBulkAction('bulk_delete', $records)
        ->assertHasNoTableBulkActionErrors();

    $completedRuns->each(fn (RestoreRun $run) => expect(RestoreRun::withTrashed()->find($run->id)?->trashed())->toBeTrue());
    expect(RestoreRun::withTrashed()->find($running->id)?->trashed())->toBeFalse();

    $bulkRun = BulkOperationRun::query()
        ->where('resource', 'restore_run')
        ->where('action', 'delete')
        ->latest('id')
        ->first();

    expect($bulkRun)->not->toBeNull();
    expect($bulkRun->skipped)->toBeGreaterThanOrEqual(1);
});
