<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\HostSystemUpdateExecutionStatus;
use App\Models\HostSystemUpdateExecutionLog;
use App\Services\DberpAuditService;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cache;

/**
 * 清理已终态更新任务的步骤明细；执行主记录长期保留。
 *
 * NOTE: 进行中、待回滚、人工恢复中、RollbackFailed 的明细永不删除。
 * NOTE: 默认不依赖 cron，由更新中心打开或更新结束后 opportunistic 触发。
 */
final class HostSystemUpdateExecutionLogPruningService
{
    public const AUDIT_ACTION = 'dberp.system_update.execution_log.pruned';

    private const CACHE_KEY = 'dberp.system_update.execution_log_prune';

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

    public function retentionDays(): int
    {
        return max(1, (int) config('dberp.system_update.execution_log_retention_days', 10));
    }

    public function countOlderThan(int $days): int
    {
        return $this->expiredLogsQuery($days)->count();
    }

    /**
     * 删除已终态任务中早于保留期的步骤明细，不删除 host_system_update_executions。
     */
    public function deleteOlderThan(int $days, bool $writeAuditTrail = true): int
    {
        $cutoff = $this->cutoff($days);
        $deleted = $this->expiredLogsQuery($days)->delete();

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

        return $deleted;
    }

    /**
     * @param  bool  $force  true 时忽略间隔锁（更新结束后调用）
     */
    public function pruneDue(bool $force = false): int
    {
        $days = $this->retentionDays();
        $intervalHours = max(1, (int) config('dberp.system_update.execution_log_prune_interval_hours', 24));

        if (! $force && ! Cache::add(self::CACHE_KEY, 1, now()->addHours($intervalHours))) {
            return 0;
        }

        $deleted = $this->deleteOlderThan($days);

        if ($force) {
            Cache::put(self::CACHE_KEY, 1, now()->addHours($intervalHours));
        }

        return $deleted;
    }

    public function pruneDueSafely(bool $force = false): int
    {
        try {
            return $this->pruneDue($force);
        } catch (\Throwable) {
            // 明细清理失败不得阻断更新中心打开或更新终态。
            return 0;
        }
    }

    private function expiredLogsQuery(int $days): Builder
    {
        return HostSystemUpdateExecutionLog::query()
            ->where('created_at', '<', $this->cutoff($days))
            ->whereHas('execution', function ($query): void {
                $query->whereNotIn('status', HostSystemUpdateExecutionStatus::maintenanceBypassValues());
            });
    }

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