<?php

use App\Jobs\Operations\BackupSetForceDeleteWorkerJob;
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 force delete job permanently deletes archived sets and their items', function () {
    $tenant = ManagedEnvironment::factory()->create(['is_current' => true]);
    $user = User::factory()->create();

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

    $item = BackupItem::create([
        'managed_environment_id' => $tenant->id,
        'backup_set_id' => $set->id,
        'policy_id' => null,
        'policy_identifier' => 'policy-1',
        'policy_type' => 'deviceConfiguration',
        'platform' => 'windows10',
        'payload' => ['id' => 'policy-1'],
        'metadata' => null,
    ]);

    $set->delete();

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

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

    expect(BackupSet::withTrashed()->find($set->id))->toBeNull();
    expect(BackupItem::withTrashed()->find($item->id))->toBeNull();

    $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((int) ($run->summary_counts['skipped'] ?? 0))->toBe(0);
    expect((int) ($run->summary_counts['failed'] ?? 0))->toBe(0);
});

test('bulk backup set force delete job skips sets referenced by restore runs', function () {
    $tenant = ManagedEnvironment::factory()->create(['is_current' => true]);
    $user = User::factory()->create();

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

    $set->delete();

    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.force_delete',
        'status' => 'running',
        'outcome' => 'pending',
        'context' => ['target_scope' => ['entra_tenant_id' => 'entra-test-tenant']],
        'summary_counts' => ['total' => 1, 'processed' => 0],
        'failure_summary' => [],
    ]);

    (new BackupSetForceDeleteWorkerJob(
        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((int) ($run->summary_counts['processed'] ?? 0))->toBe(1);
    expect((int) ($run->summary_counts['succeeded'] ?? 0))->toBe(0);
    expect((int) ($run->summary_counts['skipped'] ?? 0))->toBe(1);
    expect((int) ($run->summary_counts['failed'] ?? 0))->toBe(0);

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

    $failure = collect($run->failure_summary ?? [])
        ->first(fn ($entry) => is_array($entry) && ($entry['code'] ?? null) === 'backup_set.referenced_by_restore_runs');
    expect($failure)->not->toBeNull();
});
