<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\DberpAuditLogPruningService;
use Illuminate\Console\Command;

class DberpPruneAuditLogsCommand extends Command
{
    protected $signature = 'dberp:audit-logs-prune
                            {--days= : 保留最近若干天，删除更早的记录（默认读取 config dberp.audit.retention_days）}
                            {--dry-run : 仅统计将删除条数，不执行删除}';

    protected $description = '删除早于保留期限的审计日志（core_audit_logs）';

    public function handle(DberpAuditLogPruningService $pruning): int
    {
        $days = $this->resolveDays();

        if ($days < 1) {
            $this->error('days 须为不小于 1 的整数。');

            return self::FAILURE;
        }

        $pending = $pruning->countOlderThan($days);

        if ($this->option('dry-run')) {
            $this->info("[dry-run] 将删除 {$pending} 条（created_at 早于当前时间 {$days} 天前）。");

            return self::SUCCESS;
        }

        $deleted = $pruning->deleteOlderThan($days);
        $this->info("已删除 {$deleted} 条审计日志（保留最近 {$days} 天）。");

        return self::SUCCESS;
    }

    private function resolveDays(): int
    {
        $raw = $this->option('days');

        if ($raw === null || $raw === false || $raw === '') {
            return (int) config('dberp.audit.retention_days', 7);
        }

        return (int) $raw;
    }
}
