<?php

namespace App\Console\Commands;

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

/**
 * Prune old hourly metric snapshots to prevent unbounded table growth.
 *
 * Usage:  php artisan nova:prune-metric-snapshots
 *         php artisan nova:prune-metric-snapshots --keep-days=7
 */
class PruneMetricSnapshotsCommand extends Command
{
    protected $signature = 'nova:prune-metric-snapshots
                            {--keep-days=7 : Keep snapshots for this many days}';

    protected $description = 'Delete old hourly metric snapshots beyond the retention window';

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

        $deleted = DB::table('artwork_metric_snapshots_hourly')
            ->where('bucket_hour', '<', $cutoff)
            ->delete();

        $this->info("Pruned {$deleted} snapshot rows older than {$keepDays} days.");

        Log::info('[nova:prune-metric-snapshots] completed', [
            'deleted'   => $deleted,
            'keep_days' => $keepDays,
        ]);

        return self::SUCCESS;
    }
}
