<?php

namespace App\Console\Commands;

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

class PruneLogsCommand extends Command
{
    protected $signature = 'logs:prune {--force : Run the prune job even when retention is disabled}';
    protected $description = 'Prune logs older than the configured retention period';

    public function handle(): int
    {
        $retentionDays = (int) config('ticaga.logs.retention_days', 30);

        if ($retentionDays <= 0 && ! $this->option('force')) {
            $this->info('Log pruning skipped because retention is disabled. Use --force to override.');

            return Command::SUCCESS;
        }

        $cutoff = now()->subDays(max(1, $retentionDays));

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

        $this->info(sprintf(
            'Pruned %d log record(s) created before %s.',
            $deleted,
            $cutoff->toDateTimeString()
        ));

        return Command::SUCCESS;
    }
}
