<?php

/*
 * This file is part of the VitiCore 2.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem;

use League\Flysystem\FilesystemOperator;

final class Filesystem
{
    /**
     * @param array<string,FilesystemOperator> $filesystems
     * @param array<string,string>             $directories
     */
    public function __construct(
        private array $filesystems,
        private array $directories,
    ) {
    }

    public function fs(string $name): FilesystemOperator
    {
        if (!isset($this->filesystems[$name])) {
            throw new \InvalidArgumentException(\sprintf('Unknown filesystem "%s".', $name));
        }

        return $this->filesystems[$name];
    }

    public function pathPrefix(string $name): string
    {
        if (!isset($this->directories[$name])) {
            throw new \InvalidArgumentException(\sprintf('Unknown directory for "%s".', $name));
        }

        return mb_rtrim($this->directories[$name], \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR;
    }

    public function absolutePath(string $name, string $relativePath): string
    {
        return $this->pathPrefix($name).mb_ltrim($relativePath, \DIRECTORY_SEPARATOR);
    }

    public function exists(string $path): bool
    {
        return is_file($path);
    }

    public function readFile(string $path): string
    {
        $contents = file_get_contents($path);
        if (false === $contents) {
            throw new \RuntimeException(\sprintf('Unable to read file "%s".', $path));
        }

        return $contents;
    }
}
