<?php

declare(strict_types=1);

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

namespace App\Services\Plugin;

/**
 * 官方插件安装包本地存储路径（非 public）。
 */
final class HostPluginPackageStorage
{
    public static function baseDirectory(): string
    {
        return storage_path('app/dberp/plugins');
    }

    public static function packagesDirectory(): string
    {
        return self::baseDirectory().DIRECTORY_SEPARATOR.'packages';
    }

    public static function stagingDirectory(): string
    {
        return self::baseDirectory().DIRECTORY_SEPARATOR.'staging';
    }

    public static function ensurePackagesDirectoryExists(): void
    {
        self::ensureDirectoryExists(self::packagesDirectory());
    }

    public static function ensureStagingDirectoryExists(): void
    {
        self::ensureDirectoryExists(self::stagingDirectory());
    }

    public static function buildSafeFilename(string $pluginCode, ?string $version, ?string $originalFilename = null): string
    {
        $safeCode = self::sanitizeSegment($pluginCode, 'plugin');
        $safeVersion = self::sanitizeSegment($version ?? 'unknown', 'version');
        $extension = self::resolveExtension($originalFilename);

        if ($extension === 'tar.gz') {
            return sprintf('dberp-plugin-%s-%s.tar.gz', $safeCode, $safeVersion);
        }

        return sprintf('dberp-plugin-%s-%s.zip', $safeCode, $safeVersion);
    }

    public static function buildStagingDirectory(string $pluginCode): string
    {
        $safeCode = self::sanitizeSegment($pluginCode, 'plugin');

        return self::stagingDirectory().DIRECTORY_SEPARATOR.$safeCode.'-'.uniqid('', true);
    }

    private static function resolveExtension(?string $originalFilename): string
    {
        if ($originalFilename === null || trim($originalFilename) === '') {
            return 'zip';
        }

        $lower = strtolower(str_replace('\\', '/', trim($originalFilename)));

        if (str_ends_with($lower, '.tar.gz') || str_ends_with($lower, '.tgz')) {
            return 'tar.gz';
        }

        return 'zip';
    }

    private static function sanitizeSegment(string $value, string $fallback): string
    {
        $normalized = strtolower(trim($value));
        $normalized = preg_replace('/[^a-z0-9._-]+/', '-', $normalized) ?? $fallback;
        $normalized = trim($normalized, '-');

        return $normalized !== '' ? $normalized : $fallback;
    }

    private static function ensureDirectoryExists(string $path): void
    {
        if (! is_dir($path)) {
            mkdir($path, 0755, true);
        }
    }
}
