<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Mtc\MercuryDataModels\ScheduledTaskRun;

class PruneScheduledTaskRuns extends Command
{
    /**
     * @var string
     */
    protected $signature = 'scheduled-tasks:prune';

    /**
     * @var string
     */
    protected $description = 'Delete finished scheduled task runs older than the retention period';

    public function handle(): int
    {
        $cutoff = Carbon::now()->subDays((int) config('scheduled_tasks.retention_days', 14));

        $deleted = ScheduledTaskRun::query()
            ->finished()
            ->where('finished_at', '<', $cutoff)
            ->delete();

        $this->info("Pruned {$deleted} scheduled task runs older than {$cutoff->toDateString()}");

        return self::SUCCESS;
    }
}
