<?php

declare(strict_types=1);

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

namespace App\Services\Plugin;

use DBCore\Plugin\Contracts\PluginManagerInterface;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * 官方插件安装失败时回滚持久化状态与已落地的文件目录。
 */
final class HostPluginInstallRollback
{
    public function __construct(
        private readonly PluginManagerInterface $pluginManager,
        private readonly DberpDatabasePluginRepository $repository,
    ) {}

    public function rollbackPersistence(string $identifier): void
    {
        $normalized = trim($identifier);

        if ($normalized === '') {
            return;
        }

        try {
            if ($this->pluginManager->isInstalled($normalized)) {
                $this->repository->delete($normalized);
            }
        } catch (Throwable $exception) {
            Log::warning('dberp.plugin_center.install_rollback_persistence_failed', [
                'identifier' => $normalized,
                'exception_class' => $exception::class,
                'exception_message' => $exception->getMessage(),
            ]);
        }
    }

    public function rollbackFilesystem(string $pluginDirectory): void
    {
        $normalized = trim($pluginDirectory);

        if ($normalized === '' || ! is_dir($normalized)) {
            return;
        }

        try {
            File::deleteDirectory($normalized);
        } catch (Throwable $exception) {
            Log::warning('dberp.plugin_center.install_rollback_filesystem_failed', [
                'path' => $normalized,
                'exception_class' => $exception::class,
                'exception_message' => $exception->getMessage(),
            ]);
        }
    }
}
