<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Storage;

use App\Scolarite\Application\Port\FileStorage;

use function dirname;
use function file_put_contents;
use function is_dir;
use function is_file;
use function is_string;
use function mkdir;

use Override;

use function unlink;

final readonly class LocalFileStorage implements FileStorage
{
    public function __construct(
        private string $storagePath,
    ) {
    }

    #[Override]
    public function upload(string $path, mixed $content, string $mimeType): string
    {
        $fullPath = $this->storagePath . '/' . $path;
        $dir = dirname($fullPath);

        if (!is_dir($dir)) {
            mkdir($dir, 0o755, true);
        }

        $data = is_string($content) ? $content : '';

        file_put_contents($fullPath, $data);

        return $path;
    }

    #[Override]
    public function delete(string $path): void
    {
        $fullPath = $this->storagePath . '/' . $path;

        if (is_file($fullPath)) {
            unlink($fullPath);
        }
    }
}
