<?php

use App\Jobs\BulkRestoreRunDeleteJob;
use App\Models\BackupSet;
use App\Models\RestoreRun;
use App\Models\Tenant;
use App\Models\User;
use App\Services\BulkOperationService;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);
test('job soft deletes deletable restore runs', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

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

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

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

    $service = app(BulkOperationService::class);
    $run = $service->createRun($tenant, $user, 'restore_run', 'delete', [$completed->id, $failed->id], 2);

    $job = new BulkRestoreRunDeleteJob($run->id);
    $job->handle($service);

    $run->refresh();
    expect($run->status)->toBe('completed')
        ->and($run->processed_items)->toBe(2)
        ->and($run->succeeded)->toBe(2)
        ->and($run->failed)->toBe(0)
        ->and($run->skipped)->toBe(0);

    expect(RestoreRun::withTrashed()->find($completed->id)?->trashed())->toBeTrue();
    expect(RestoreRun::withTrashed()->find($failed->id)?->trashed())->toBeTrue();
});

test('job skips non-deletable restore runs and records skip reasons', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create();

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

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

    $service = app(BulkOperationService::class);
    $run = $service->createRun($tenant, $user, 'restore_run', 'delete', [$running->id], 1);

    $job = new BulkRestoreRunDeleteJob($run->id);
    $job->handle($service);

    $run->refresh();
    expect($run->status)->toBe('completed')
        ->and($run->processed_items)->toBe(1)
        ->and($run->succeeded)->toBe(0)
        ->and($run->failed)->toBe(0)
        ->and($run->skipped)->toBe(1);

    expect($run->failures[0]['type'] ?? null)->toBe('skipped');
    expect($run->failures[0]['reason'] ?? '')->toContain('Not deletable');

    expect(RestoreRun::withTrashed()->find($running->id)?->trashed())->toBeFalse();
});
