<?php

use App\Jobs\BulkBackupSetRestoreJob;
use App\Jobs\Operations\BackupSetRestoreWorkerJob;
use App\Models\BackupItem;
use App\Models\BackupSet;
use App\Models\OperationRun;
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\Queue;

uses(RefreshDatabase::class);

test('bulk backup set restore job initializes deduplicated totals only once across launcher replays', function () {
    Queue::fake();

    $tenant = ManagedEnvironment::factory()->create(['is_current' => true]);
    $user = User::factory()->create();

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

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

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

    $job = new BulkBackupSetRestoreJob(
        tenantId: (int) $tenant->getKey(),
        userId: (int) $user->getKey(),
        backupSetIds: [(int) $firstSet->getKey(), (int) $firstSet->getKey(), (int) $secondSet->getKey()],
        operationRun: $run,
        context: ['target_scope' => ['entra_tenant_id' => 'entra-test-tenant']],
    );

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

    $run->refresh();

    expect($run->summary_counts ?? [])->toMatchArray([
        'total' => 2,
        'processed' => 0,
        'succeeded' => 0,
        'failed' => 0,
        'skipped' => 0,
    ]);

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

    $run->refresh();

    expect($run->summary_counts ?? [])->toMatchArray([
        'total' => 2,
        'processed' => 0,
        'succeeded' => 0,
        'failed' => 0,
        'skipped' => 0,
    ]);
});

test('bulk backup set restore job restores 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();

    $set->refresh();
    expect($set->trashed())->toBeTrue();
    expect(BackupItem::withTrashed()->find($item->id)?->trashed())->toBeTrue();

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

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

    $set->refresh();
    expect($set->trashed())->toBeFalse();

    $item->refresh();
    expect($item->trashed())->toBeFalse();

    $run->refresh();
    expect($run->status)->toBe('completed');
    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 restore job skips active sets', 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,
    ]);

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

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

    $set->refresh();
    expect($set->trashed())->toBeFalse();

    $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);
});
