<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Service;

use Contao\CoreBundle\Filesystem\VirtualFilesystemInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\Uid\Uuid;

class FileUploader
{
    public function __construct(private readonly SluggerInterface $slugger)
    {
    }

    public function upload(VirtualFilesystemInterface $storage, UploadedFile $file): ?Uuid
    {
        $originalFilename = pathinfo($file->getClientOriginalName(), \PATHINFO_FILENAME);
        $safeFilename = $this->slugger->slug($originalFilename);
        $fileName = strtolower($safeFilename->toString()).'-'.uniqid().'.'.$file->guessExtension();

        $storage->write($fileName, $file->getContent());

        return $storage->get($fileName)?->getUuid();
    }
}
