<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;
use App\Models\HostSystemUpdateExecution;

/** 在启动新 CLI 进程前，仅清理 Laravel 文件型启动缓存。 */
final class HostSystemUpdateBootstrapCacheCleaner
{
    public function __construct(
        private readonly HostSystemUpdateExecutionLogger $executionLogger,
    ) {}

    public function clear(HostSystemUpdateExecution $execution): void
    {
        $startedAt = now()->utc();
        $step = 'clear_bootstrap_cache';
        $cacheDirectory = base_path('bootstrap/cache');

        $this->executionLogger->logStepStarted(
            $execution,
            $step,
            (string) __('dberp.system_update.post_apply.log.bootstrap_cache_clear_started'),
        );

        try {
            $cacheFiles = glob($cacheDirectory.DIRECTORY_SEPARATOR.'*.php') ?: [];

            foreach ($cacheFiles as $cacheFile) {
                if (! is_file($cacheFile) || @unlink($cacheFile)) {
                    clearstatcache(true, $cacheFile);

                    continue;
                }

                throw HostSystemUpdatePostApplyException::cacheClearFailed('bootstrap/cache');
            }

            clearstatcache(true, $cacheDirectory);

            $this->executionLogger->logStepCompleted(
                $execution,
                $step,
                (string) __('dberp.system_update.post_apply.log.bootstrap_cache_cleared'),
                ['removed_bootstrap_cache_files' => count($cacheFiles)],
                $startedAt,
            );
        } catch (HostSystemUpdatePostApplyException $exception) {
            $this->executionLogger->logStepFailed(
                $execution,
                $step,
                $exception->userFacingMessage(),
                $exception->errorCode(),
                $exception->userFacingMessage(),
                ['cache_directory' => $cacheDirectory],
                $startedAt,
            );

            throw $exception;
        }
    }
}
