<?php

use App\Jobs\BulkRestoreRunDeleteJob;
use App\Jobs\Operations\RestoreRunDeleteWorkerJob;
use App\Models\BackupSet;
use App\Models\OperationRun;
use App\Models\RestoreRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\OperationRunService;
use App\Services\Operations\TargetScopeConcurrencyLimiter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;

uses(RefreshDatabase::class);
test('bulk restore run delete enqueues worker jobs and sets total count', function () {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

    Bus::fake();

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'restore_run.delete',
        'status' => 'queued',
        'outcome' => 'pending',
        'summary_counts' => [],
        'failure_summary' => [],
        'context' => [
            'target_scope' => ['directory_context_id' => 1],
        ],
    ]);

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

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

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

    (new BulkRestoreRunDeleteJob(
        tenantId: $tenant->id,
        userId: $user->id,
        restoreRunIds: [$completed->id, $failed->id],
        operationRun: $run,
    ))->handle(app(OperationRunService::class));

    $run->refresh();

    expect($run->status)->toBe('running')
        ->and($run->summary_counts['total'] ?? null)->toBe(2);

    Bus::assertDispatchedTimes(RestoreRunDeleteWorkerJob::class, 2);
});

test('worker soft deletes deletable restore runs', function () {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'restore_run.delete',
        'status' => 'running',
        'outcome' => 'pending',
        'summary_counts' => ['total' => 2],
        'failure_summary' => [],
        'context' => [
            'target_scope' => ['directory_context_id' => 1],
        ],
    ]);

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

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

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

    $runs = app(OperationRunService::class);
    $limiter = app(TargetScopeConcurrencyLimiter::class);

    (new RestoreRunDeleteWorkerJob(
        tenantId: $tenant->id,
        userId: $user->id,
        restoreRunId: $completed->id,
        operationRun: $run,
    ))->handle($runs, $limiter);

    (new RestoreRunDeleteWorkerJob(
        tenantId: $tenant->id,
        userId: $user->id,
        restoreRunId: $failed->id,
        operationRun: $run,
    ))->handle($runs, $limiter);

    $run->refresh();
    expect($run->status)->toBe('completed')
        ->and($run->outcome)->toBe('succeeded')
        ->and($run->summary_counts['processed'] ?? null)->toBe(2)
        ->and($run->summary_counts['succeeded'] ?? null)->toBe(2)
        ->and((int) ($run->summary_counts['failed'] ?? 0))->toBe(0)
        ->and((int) ($run->summary_counts['skipped'] ?? 0))->toBe(0);

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

test('worker skips non-deletable restore runs', function () {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'restore_run.delete',
        'status' => 'running',
        'outcome' => 'pending',
        'summary_counts' => ['total' => 1],
        'failure_summary' => [],
        'context' => [
            'target_scope' => ['directory_context_id' => 1],
        ],
    ]);

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

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

    $runs = app(OperationRunService::class);
    $limiter = app(TargetScopeConcurrencyLimiter::class);

    (new RestoreRunDeleteWorkerJob(
        tenantId: $tenant->id,
        userId: $user->id,
        restoreRunId: $running->id,
        operationRun: $run,
    ))->handle($runs, $limiter);

    $run->refresh();
    expect($run->status)->toBe('completed')
        ->and($run->outcome)->toBe('succeeded')
        ->and($run->summary_counts['processed'] ?? null)->toBe(1)
        ->and((int) ($run->summary_counts['succeeded'] ?? 0))->toBe(0)
        ->and((int) ($run->summary_counts['failed'] ?? 0))->toBe(0)
        ->and($run->summary_counts['skipped'] ?? null)->toBe(1);

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