<?php

use App\Jobs\Operations\BackupSetDeleteWorkerJob;
use App\Models\BackupItem;
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;

uses(RefreshDatabase::class);
test('bulk backup set delete job archives sets and cascades to backup items', function () {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

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

    $items = collect(range(1, 2))->map(function (int $i) use ($tenant, $set) {
        return BackupItem::create([
            'managed_environment_id' => $tenant->id,
            'backup_set_id' => $set->id,
            'policy_id' => null,
            'policy_identifier' => 'policy-'.$i,
            'policy_type' => 'deviceConfiguration',
            'platform' => 'windows10',
            'payload' => ['id' => 'policy-'.$i],
            'metadata' => null,
        ]);
    });

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'initiator_name' => $user->name,
        'type' => 'backup_set.delete',
        'status' => 'running',
        'outcome' => 'pending',
        'context' => ['target_scope' => ['entra_tenant_id' => 'entra-test-tenant']],
        'summary_counts' => ['total' => 1, 'processed' => 0],
    ]);

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

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

    expect(BackupSet::withTrashed()->find($set->id)?->trashed())->toBeTrue();

    $items->each(function (BackupItem $item) {
        expect(BackupItem::withTrashed()->find($item->id)?->trashed())->toBeTrue();
    });
});

test('bulk backup set delete job archives sets even when referenced by restore runs', function () {
    $tenant = ManagedEnvironment::factory()->create();
    $user = User::factory()->create();

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

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

    $run = OperationRun::factory()->create([
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $user->getKey(),
        'initiator_name' => $user->name,
        'type' => 'backup_set.delete',
        'status' => 'running',
        'outcome' => 'pending',
        'context' => ['target_scope' => ['entra_tenant_id' => 'entra-test-tenant']],
        'summary_counts' => ['total' => 1, 'processed' => 0],
    ]);

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

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

    expect(BackupSet::withTrashed()->find($set->id)?->trashed())->toBeTrue();
    expect(RestoreRun::query()->where('backup_set_id', $set->id)->exists())->toBeTrue();
});
