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

const multerImageStore = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir = `./public/images/`;
    fs.stat(dir, (exist) => {
      if (exist) {
        fs.mkdir(dir, () => {});
      }
      cb(null, dir);
    });
  },

  filename: (req, file, cb) => {
    cb(
      null,
      file.fieldname +
        "_" +
        Date.now() +
        "_" +
        file.originalname.replace(/ /g, "_")
    );
  },
});
exports.uploadImage = multer({
  storage: multerImageStore,
  limits: {
    fileSize: 50 * 1024 * 1024, // 10 MB,
  },
  fileFilter: (req, file, cb) => {
    // const fileTypes =
    //   /jpeg|mpeg|heif|heic|bmp|png|webp|jpg|svg|mp4|m4p|m4v|mov|avi|wmv|flv|x-flv|webm|mkv|ogg|quicktime|x-matroska/;
    const fileTypes = /jpeg|png|webp|jpg|avif/;
    const extname = fileTypes.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimeType = fileTypes.test(file.mimetype);
    if (mimeType && extname) {
      req.file = file;
      return cb(null, true);
    } else {
      // req.body.isInvalidType = true;
      return cb(
        "Invalid file type. Please upload image in JPEG, PNG, WEBP, JPG, OR AVIF",
        false
      );
    }
  },
});
