const multer = require("multer");
const fs = require("fs");
const path = require("path");

// const storage = multer.diskStorage({
//   destination: function (req, file, cb) {
//     if (!fs.existsSync("uploads")) {
//       fs.mkdirSync("uploads");
//     }

//     if (!fs.existsSync("uploads/images")) {
//       fs.mkdirSync("uploads/images");
//     }

//     cb(null, "uploads/images");
//   },
//   filename: function (req, file, cb) {
//     const fileExt = path.extname(file.originalname);
//     const fileName =
//       file.originalname
//         .replace(fileExt, "")
//         .toLowerCase()
//         .split(" ")
//         .join("-") +
//       "___" +
//       Date.now();
//     cb(null, fileName + fileExt);
//   },
// });
const storage = multer.memoryStorage()
const whitelist = [
  "image/png",
  "image/jpeg",
  "image/jpg",
  "image/webp",
  "image/gif",
];
const upload = multer({
  storage: storage,
  fileFilter: function (req, file, cb) {
      var ext = path.extname(file.originalname);
    if (!whitelist.includes(file.mimetype)) {
      return cb(new Error("file type is not allowed"), false);
    }
    req.on("aborted", () => {
      file.stream.on("end", () => {
        console.log("Cancel the upload");
        cb(new Error("Cancel."), false);
      });
      file.stream.emit("end");
    });
    cb(null, true);
  },
});
module.exports = {
  upload,
};
