<?php

namespace App\Console\Commands;

use App\Models\AttendanceEvent;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class PurgeSnapshots extends Command
{
    protected $signature = 'attendance:purge-snapshots {--days=60 : Retention window in days}';

    protected $description = 'Delete punch snapshot images older than the retention window and clear their snapshot_path.';

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

        $events = AttendanceEvent::query()
            ->whereNotNull('snapshot_path')
            ->where('ts', '<', $cutoff)
            ->get();

        $count = 0;

        foreach ($events as $event) {
            if ($event->snapshot_path && Storage::disk('local')->exists($event->snapshot_path)) {
                Storage::disk('local')->delete($event->snapshot_path);
            }

            $event->update(['snapshot_path' => null]);
            $count++;
        }

        $this->info("Purged {$count} snapshot(s) older than {$days} days.");

        return self::SUCCESS;
    }
}
