<?php

use App\Jobs\ApplyBackupScheduleRetentionJob;
use App\Models\BackupSchedule;
use App\Models\BackupScheduleRun;
use App\Models\BackupSet;
use Filament\Facades\Filament;

test('retention keeps last N backup sets per schedule', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

    $schedule = BackupSchedule::query()->create([
        'tenant_id' => $tenant->id,
        'name' => 'Nightly',
        '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,
    ]);

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

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

    // Oldest → newest
    $scheduledFor = now('UTC')->startOfMinute()->subMinutes(10);
    foreach ($sets as $set) {
        BackupScheduleRun::query()->create([
            'backup_schedule_id' => $schedule->id,
            'tenant_id' => $tenant->id,
            'scheduled_for' => $scheduledFor,
            'status' => BackupScheduleRun::STATUS_SUCCESS,
            'summary' => ['policies_total' => 0, 'policies_backed_up' => 0, 'errors_count' => 0],
            'backup_set_id' => $set->id,
        ]);
        $scheduledFor = $scheduledFor->addMinute();
    }

    ApplyBackupScheduleRetentionJob::dispatchSync($schedule->id);

    $kept = $sets->take(-2);
    $deleted = $sets->take(3);

    foreach ($kept as $set) {
        $this->assertDatabaseHas('backup_sets', [
            'id' => $set->id,
            'deleted_at' => null,
        ]);
    }

    foreach ($deleted as $set) {
        $this->assertSoftDeleted('backup_sets', ['id' => $set->id]);
    }
});
