<?php

namespace App\Console\Commands;

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

class PruneOldData extends Command
{
    protected $signature   = 'numerix:prune {--days=30 : Delete results older than N days}';
    protected $description = 'Prune old phone results to keep the database lean';

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

        $this->info("Pruning phone_results older than {$days} days ({$cutoff->toDateString()})...");

        // Delete phone_results
        $deleted = DB::table('phone_results')
            ->where('created_at', '<', $cutoff)
            ->delete();
        $this->info("Deleted {$deleted} phone_result records.");

        // Delete stale upload export files
        $staleUploads = DB::table('uploads')
            ->where('created_at', '<', $cutoff)
            ->where('status', 'completed')
            ->select(['id', 'file_path', 'tenant_id'])
            ->get();

        $filesDeleted = 0;
        foreach ($staleUploads as $upload) {
            if ($upload->file_path && Storage::disk('local')->exists($upload->file_path)) {
                Storage::disk('local')->delete($upload->file_path);
                $filesDeleted++;
            }
        }
        $this->info("Deleted {$filesDeleted} temporary files.");

        return self::SUCCESS;
    }
}
