const fs = require('fs').promises;
const path = require('path');
const PROJECTS_DIR = path.join('.');

async function createFolder(name) {
   const projectDir = path.join(PROJECTS_DIR, `${name}`);
   try {
      await fs.access(projectDir);
   } catch (error) {
      if (error.code === 'ENOENT') {
         await fs.mkdir(projectDir, { recursive: true });
      } else {
         throw error;
      }
   }
   return projectDir;
}

async function deleteFolder(name) {
   const projectDir = path.join(PROJECTS_DIR, `${name}`);
   try {
      await fs.access(projectDir);
      await fs.rm(projectDir, { recursive: true, force: true });
   } catch (error) {
      if (error.code !== 'ENOENT') {
         throw error;
      }
   }
}

async function scanAllImages(dir = 'storage') {
   const projectDir = path.join(PROJECTS_DIR, dir);
   let results = [];

   async function scanDirectory(directory) {
      const files = await fs.readdir(directory);
      for (const file of files) {
         const filePath = path.join(directory, file);
         const stat = await fs.stat(filePath);
         if (stat.isDirectory()) {
            await scanDirectory(filePath);
         } else if (file.endsWith('.jpg')) {
            results.push(filePath);
         }
      }
   }

   await scanDirectory(projectDir);
   return results;
}

async function saveFile(filePath, content) {
   if (Buffer.isBuffer(content)) {
      await fs.writeFile(filePath, content);
   } else {
      throw new Error('Content must be a buffer');
   }
}

async function getFile(name) {
   const filePath = path.join(PROJECTS_DIR, `${name}`);
   return await fs.readFile(filePath);
}

async function deleteFile(name) {
   const filePath = path.join(PROJECTS_DIR, `${name}`);
   try {
       await fs.access(filePath); // Vérifie si le fichier existe
       await fs.rm(filePath); // Supprime le fichier
       return `File ${filePath} deleted successfully.`;
   } catch (error) {
       if (error.code === 'ENOENT') {
           return `File ${filePath} does not exist.`;
       } else {
           throw error; // Relance l'erreur si ce n'est pas une erreur de fichier introuvable
       }
   }
}

module.exports = {
   createFolder,
   deleteFolder,
   scanAllImages,
   saveFile,
   getFile,
   deleteFile
};