<?php

namespace NoahVet\Reef\Domain\Tool;

class FileTool implements FileToolInterface
{
    #[\Override]
    public static function forceFilePutContents(string $filePath, mixed $contents): void
    {
        if (!\is_string($contents)) {
            if (\is_scalar($contents) || $contents instanceof \Stringable) {
                $contents = (string) $contents;
            } else {
                $encodedContents = \json_encode($contents);
                $contents = false === $encodedContents ? '' : $encodedContents;
            }
        }

        if (\str_starts_with($filePath, './')) {
            $filePath = \substr($filePath, 2);
        }

        $parts = \explode('/', $filePath);
        $file = \array_pop($parts);
        $directory = '';

        foreach ($parts as $part) {
            if (
                !\is_file($part)
                && !\is_dir($directory .= "$part/")
            ) {
                \mkdir($directory);
            }
        }

        \file_put_contents("$directory/$file", $contents);
    }

    #[\Override]
    public static function forceRemoveDirectory(string $directory): bool
    {
        try {
            /** @var array<string> $dir */
            $dir = \scandir($directory);
            foreach (\array_diff($dir, ['.', '..']) as $file) {
                (\is_dir("$directory/$file"))
                    ? self::forceRemoveDirectory("$directory/$file")
                    : \unlink("$directory/$file");
            }

            return \rmdir($directory);
        } catch (\Exception) {
            return false;
        }
    }
}
