<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class UploaderService
{
    public const DIR_PP = 'pp';
    public const DIR_MOD = 'mods';
    public const DIR_FILE = 'files';

    public function __construct(private readonly string $uploadDir) {}

    public function getUploadDir(string $sousDir = self::DIR_FILE): string
    {
        return $this->uploadDir . '/' . $sousDir;
    }

    public function upload(UploadedFile $file, string $sousDir = self::DIR_FILE, bool $keepOriginalName = false): string
    {
        $dossier = $this->uploadDir . '/' . $sousDir;

        if (!is_dir($dossier)) {
            mkdir($dossier, 0755, true);
        }

        if ($keepOriginalName) {
            // Garde le nom original du fichier
            $nom = $file->getClientOriginalName();
            if (file_exists($dossier . '/' . $nom)) {
                throw new \RuntimeException("Le mod '$nom' existe déjà.");
            }
        } else {
            // Génère un nom unique (comportement par défaut)
            $nom = uniqid() . '.' . $file->guessExtension();
        }

        $file->move($dossier, $nom);

        return $nom;
    }

    public function delete(string $nom, string $sousDir = self::DIR_FILE): ?bool
    {
        $chemin = $this->uploadDir . '/' . $sousDir . '/' . $nom;

        if (file_exists($chemin)) {
            return unlink($chemin);
        }

        return null; // Fichier non trouvé
    }
}
