<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\DberpAuditLog;
use Carbon\CarbonInterface;

final class DberpAuditLogPruningService
{
    public function __construct(
        private readonly DberpAuditService $auditService,
    ) {}

    public function countOlderThan(int $days): int
    {
        return DberpAuditLog::query()
            ->where('created_at', '<', $this->cutoff($days))
            ->count();
    }

    /**
     * 删除创建时间早于「当前时间减去 $days 天」的审计记录，并可写入一条清理留痕。
     */
    public function deleteOlderThan(int $days, bool $writeAuditTrail = true): int
    {
        $cutoff = $this->cutoff($days);

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

        if ($writeAuditTrail && $deleted > 0) {
            $this->auditService->log('dberp.audit_log.pruned', null, null, [
                'deleted_count' => $deleted,
                'older_than_days' => $days,
                'cutoff_at' => $cutoff->toIso8601String(),
            ]);
        }

        return $deleted;
    }

    private function cutoff(int $days): CarbonInterface
    {
        return now()->subDays($days);
    }
}
