<?php

declare(strict_types=1);

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;
    }
}
