<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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);
    }
}
