<?php

declare(strict_types=1);

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

namespace App\Services\Install;

use Illuminate\Support\Facades\File;

/**
 * Web 安装阶段须存在的 Laravel 可写目录。
 */
final class InstallRuntimeDirectorySupport
{
    /**
     * @var list<string>
     */
    private const WRITABLE_DIRECTORY_PREFIXES = [
        'storage/app',
        'storage/app/public',
        'storage/framework',
        'storage/framework/cache',
        'storage/framework/cache/data',
        'storage/framework/sessions',
        'storage/framework/testing',
        'storage/framework/views',
        'storage/logs',
        'bootstrap/cache',
    ];

    /**
     * @var list<string>
     */
    private const GITKEEP_RELATIVE_PATHS = [
        'storage/logs/.gitkeep',
        'storage/framework/cache/data/.gitkeep',
        'storage/framework/sessions/.gitkeep',
        'storage/framework/views/.gitkeep',
        'storage/framework/testing/.gitkeep',
        'storage/app/public/.gitkeep',
        'bootstrap/cache/.gitkeep',
    ];

    public static function ensureWritableDirectories(string $applicationRoot): void
    {
        foreach (self::WRITABLE_DIRECTORY_PREFIXES as $relative) {
            File::ensureDirectoryExists(self::join($applicationRoot, $relative));
        }

        foreach (self::GITKEEP_RELATIVE_PATHS as $relative) {
            $path = self::join($applicationRoot, $relative);
            File::ensureDirectoryExists(dirname($path));
            File::put($path, '');
        }
    }

    private static function join(string $root, string $relative): string
    {
        return $root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
    }
}
