<?php

declare(strict_types=1);

namespace App\Services\Install;

use Illuminate\Support\Facades\File;

/**
 * 分阶段安装单步执行锁（基于文件 flock，兼容未安装时的 file 缓存环境）。
 */
final class WebInstallStepLock
{
    /** @var array<string, resource> */
    private array $handles = [];

    public function __construct(
        private readonly ?string $lockDirectory = null,
    ) {}

    public function tryAcquire(string $installId): bool
    {
        $path = $this->pathFor($installId);
        File::ensureDirectoryExists(dirname($path));

        $handle = fopen($path, 'c+');
        if ($handle === false) {
            return false;
        }

        if (! flock($handle, LOCK_EX | LOCK_NB)) {
            fclose($handle);

            return false;
        }

        $this->handles[$installId] = $handle;

        return true;
    }

    public function release(string $installId): void
    {
        if (! isset($this->handles[$installId])) {
            return;
        }

        flock($this->handles[$installId], LOCK_UN);
        fclose($this->handles[$installId]);
        unset($this->handles[$installId]);
    }

    private function pathFor(string $installId): string
    {
        return ($this->lockDirectory ?? storage_path('framework/dberp-install/locks'))
            .DIRECTORY_SEPARATOR.$installId.'.lock';
    }
}
