<?php

declare(strict_types=1);

use App\Jobs\ApplyBackupScheduleRetentionJob;
use App\Models\BackupSchedule;
use App\Models\BackupSet;
use App\Models\OperationRun;
use App\Support\OperationRunType;

it('completes backup retention runs without persisting terminal notifications for system runs', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

    $schedule = BackupSchedule::query()->create([
        'managed_environment_id' => (int) $tenant->getKey(),
        'name' => 'Retention Regression',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 2,
    ]);

    $sets = collect(range(1, 4))->map(function (int $index) use ($tenant): BackupSet {
        return BackupSet::query()->create([
            'managed_environment_id' => (int) $tenant->getKey(),
            'name' => 'Retention Set '.$index,
            'status' => 'completed',
            'item_count' => 0,
            'completed_at' => now()->subMinutes(10 - $index),
        ]);
    });

    $completedAt = now('UTC')->startOfMinute()->subMinutes(8);

    foreach ($sets as $set) {
        OperationRun::query()->create([
            'workspace_id' => (int) $tenant->workspace_id,
            'managed_environment_id' => (int) $tenant->getKey(),
            'user_id' => null,
            'initiator_name' => 'System',
            'type' => 'backup_schedule_run',
            'status' => 'completed',
            'outcome' => 'succeeded',
            'run_identity_hash' => hash('sha256', 'ops-ux-retention-regression:'.$schedule->id.':'.$set->id),
            'summary_counts' => [],
            'failure_summary' => [],
            'context' => [
                'backup_schedule_id' => (int) $schedule->id,
                'backup_set_id' => (int) $set->id,
            ],
            'started_at' => $completedAt,
            'completed_at' => $completedAt,
        ]);

        $completedAt = $completedAt->addMinute();
    }

    ApplyBackupScheduleRetentionJob::dispatchSync((int) $schedule->getKey());

    $retentionRun = OperationRun::query()
        ->where('managed_environment_id', (int) $tenant->getKey())
        ->where('type', OperationRunType::BackupScheduleRetention->value)
        ->latest('id')
        ->first();

    expect($retentionRun)->not->toBeNull();
    expect($retentionRun?->status)->toBe('completed');
    expect($retentionRun?->outcome)->toBe('succeeded');
    expect((int) ($retentionRun?->summary_counts['processed'] ?? 0))->toBe(2);
    expect($user->notifications()->count())->toBe(0);
    $this->assertDatabaseCount('notifications', 0);
})->group('ops-ux');
