<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

/**
 * 系统更新包本地存储路径（非 public）。
 */
final class HostSystemUpdatePackageStorage
{
    public static function packagesDirectory(): string
    {
        return HostSystemUpdateWorkspaceStorage::packagesDirectory();
    }

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

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

        if ($extension === HostSystemUpdatePackageArchiveFormat::TAR_GZ) {
            return sprintf('dberp-update-%s-%s.tar.gz', $safeId, $safeVersion);
        }

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

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

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

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

        return HostSystemUpdatePackageArchiveFormat::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;
    }
}
