<?php

namespace App\Console\Commands;

use App\Models\AuditEvent;
use App\Models\Setting;
use Illuminate\Console\Command;

/**
 * Enforce the audit-log retention policy: delete audit_events older than the
 * configured number of days. The policy lives in the `audit_retention_days`
 * setting (managed from the Audit page); empty or 0 means "keep forever".
 *
 * Scheduled daily in routes/console.php.
 */
class PruneAudit extends Command
{
    protected $signature = 'clusev:prune-audit';

    protected $description = 'Prune audit_events older than the configured retention window';

    public function handle(): int
    {
        $days = (int) Setting::get('audit_retention_days', '0');

        if ($days <= 0) {
            $this->info('Aufbewahrung unbegrenzt — nichts zu tun');

            return self::SUCCESS;
        }

        $deleted = AuditEvent::where('created_at', '<', now()->subDays($days))->delete();

        $this->info("Aufbewahrung {$days} Tage — {$deleted} Audit-Einträge gelöscht");

        return self::SUCCESS;
    }
}
