<?php

namespace App\Jobs;

use App\Models\Job;
use App\Models\JobRun;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class PruneOldJobRuns implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        // For each job, keep only the last N runs
        foreach (Job::all() as $job) {
            $job->jobRuns()
                ->orderByDesc('id')
                ->skip(config('jobs.pruneOldJobRuns.max_runs_per_job'))
                ->delete();
        }
    }
}
