<?php

declare(strict_types=1);

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