<?php

namespace App\Console\Commands;

use App\Models\LocationCheckResult;
use Illuminate\Console\Command;

/**
 * Delete location_check_results older than --days. Buckets keep the
 * historical data so this is safe — uptime queries beyond 7 days hit
 * uptime_buckets, not raw rows.
 *
 * Default 7 days because that's the cutoff at which UptimeService stops
 * reading raw results.
 */
class PruneOldCheckResultsCommand extends Command
{
    protected $signature = 'noc:prune-check-results {--days=7}';
    protected $description = 'Delete old per-location check results (already aggregated into buckets)';

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

        // Chunk the delete so a 100M-row table doesn't lock the DB. Most
        // databases page-lock during a single huge DELETE, blocking writes.
        $deleted = 0;
        do {
            $rows = LocationCheckResult::where('checked_at', '<', $cutoff)
                ->limit(5000)
                ->delete();
            $deleted += $rows;
        } while ($rows > 0);

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