<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class PruneMetricsCommand extends Command
{
    protected $signature = 'noc:prune-metrics {--days=30}';
    protected $description = 'Delete raw server_metrics older than N days';

    public function handle(): int
    {
        $days = max(1, (int) $this->option('days'));
        $cutoff = now()->subDays($days);

        // Delete in chunks so we never lock the table for long.
        $deleted = 0;
        do {
            $count = DB::table('server_metrics')
                ->where('measured_at', '<', $cutoff)
                ->limit(5000)
                ->delete();
            $deleted += $count;
        } while ($count > 0);

        $this->info("Pruned {$deleted} raw metric rows older than {$days}d");
        return self::SUCCESS;
    }
}
