<?php

declare(strict_types=1);

use App\Jobs\BulkBackupSetDeleteJob;
use App\Jobs\Operations\BackupSetDeleteWorkerJob;
use App\Models\BackupSet;
use App\Models\OperationRun;
use App\Services\OperationRunService;
use App\Services\Operations\TargetScopeConcurrencyLimiter;
use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Cache;

it('dispatches backup set delete workers and sets total', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'backup_set.delete',
        'status' => 'queued',
        'summary_counts' => [],
        'context' => [
            'target_scope' => [
                'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
            ],
        ],
    ]);

    Bus::fake();

    $job = new BulkBackupSetDeleteJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        backupSetIds: [3, 2, 1],
        operationRun: $run,
        context: [],
    );

    $job->handle(app(OperationRunService::class));

    $run = $run->fresh();

    expect($run)->not->toBeNull();
    expect($run?->status)->toBe('running');
    expect($run?->summary_counts['total'] ?? null)->toBe(3);

    Bus::assertDispatched(BackupSetDeleteWorkerJob::class, 3);
})->group('ops-ux');

it('archives only active backup sets and updates summary counts', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $active = BackupSet::factory()->create([
        'managed_environment_id' => $tenant->id,
        'deleted_at' => null,
    ]);

    $alreadyArchived = BackupSet::factory()->create([
        'managed_environment_id' => $tenant->id,
        'deleted_at' => null,
    ]);
    $alreadyArchived->delete();

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->id,
        'user_id' => $user->id,
        'type' => 'backup_set.delete',
        'status' => 'running',
        'summary_counts' => [
            'total' => 2,
            'processed' => 0,
            'failed' => 0,
        ],
        'context' => [
            'target_scope' => [
                'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
            ],
        ],
    ]);

    $lock = new class implements Lock
    {
        public function get($callback = null): bool
        {
            return true;
        }

        public function block($seconds, $callback = null): bool
        {
            return true;
        }

        public function release(): bool
        {
            return true;
        }

        public function owner(): string
        {
            return 'test';
        }

        public function forceRelease(): void
        {
            // no-op
        }
    };

    Cache::partialMock()
        ->shouldReceive('lock')
        ->andReturn($lock);

    (new BackupSetDeleteWorkerJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        backupSetId: (int) $active->getKey(),
        operationRun: $run,
    ))->handle(app(OperationRunService::class), app(TargetScopeConcurrencyLimiter::class));

    (new BackupSetDeleteWorkerJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        backupSetId: (int) $alreadyArchived->getKey(),
        operationRun: $run,
    ))->handle(app(OperationRunService::class), app(TargetScopeConcurrencyLimiter::class));

    $run = $run->fresh();

    expect($active->fresh()?->trashed())->toBeTrue();
    expect($alreadyArchived->fresh()?->trashed())->toBeTrue();

    expect($run)->not->toBeNull();
    expect($run?->status)->toBe('completed');
    expect($run?->outcome)->toBe('succeeded');

    expect($run?->summary_counts['processed'] ?? null)->toBe(2);
    expect($run?->summary_counts['succeeded'] ?? null)->toBe(1);
    expect($run?->summary_counts['deleted'] ?? null)->toBe(1);
    expect($run?->summary_counts['skipped'] ?? null)->toBe(1);
})->group('ops-ux');
