<?php declare(strict_types=1);

namespace App\Engine\Admin\Storage;

readonly class StorageUploader
{

    public const DEFAULT_STORAGE_LOCATION_PREFIX = "upload/";

    public function __construct(
        private \Symfony\Component\HttpKernel\KernelInterface $kernel,
    ) {
    }

    /**
     * @param callable(string $path): void $setFile
     */
    public function processFile(\Symfony\Component\Form\FormInterface $form, string $fieldName, string $recordTitle, callable $setFile, ?string $storageLocation = null): void
    {
        $fileElement = $form->get($fieldName);
        $file = $fileElement->get("file")->getData();
        $fileClear = $fileElement->has("file_clear") && $fileElement->get("file_clear")->getData();
        if ($fileClear) {
            $setFile("");
            return;
        }

        if (!($file instanceof \Symfony\Component\HttpFoundation\File\UploadedFile)) {
            return;
        }

        $fileServerFilePath = $this->processUploadedFile(uploadedFile: $file, recordName: \App\Engine\Utills\StringHelpers::urlize("$fieldName-$recordTitle"), storageLocation: $storageLocation);
        if (!$fileServerFilePath) {
            return;
        }
        $setFile($fileServerFilePath);
    }

    protected function processUploadedFile(\Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile, string $recordName, ?string $storageLocation = null): string
    {
        $storageLocation ??= self::DEFAULT_STORAGE_LOCATION_PREFIX;
        $fileName = "$recordName-" . $uploadedFile->getClientOriginalName();
        $relativeDirPath = "/data/storage/$storageLocation";
        $relativePath = $relativeDirPath . $fileName;
        $newFileDirPath = $this->kernel->getProjectDir() . "/public" . $relativeDirPath;
        $uploadedFile->move(directory: $newFileDirPath, name: $fileName);

        return $relativePath;
    }

}