<?php

declare(strict_types=1);

namespace App\Console\Commands;

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

class PruneStoredReportsCommand extends Command
{
    /**
     * @var string
     */
    protected $signature = 'stored-reports:prune {--days= : Number of days to retain reports}';

    /**
     * @var string
     */
    protected $description = 'Delete stored reports older than the retention period';

    public function handle(): int
    {
        $days = (int) ($this->option('days') ?: config('tenantpilot.stored_reports.retention_days', 90));

        if ($days < 1) {
            $this->error('Retention days must be at least 1.');

            return self::FAILURE;
        }

        $cutoff = now()->subDays($days);

        $deleted = StoredReport::query()
            ->where('created_at', '<', $cutoff)
            ->delete();

        $this->info("Deleted {$deleted} stored report(s) older than {$days} days.");

        return self::SUCCESS;
    }
}
