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

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    if (file.fieldname === "catalog_pdf") {
      cb(null, "uploads/products/pdf");
    } else if (file.fieldname === "gallery_images") {
      cb(null, "uploads/products/gallery");
    } else {
      cb(null, "uploads/products/images");
    }
  },

  filename: (req, file, cb) => {
    cb(
      null,
      Date.now() +
        "-" +
        Math.round(Math.random() * 1e9) +
        path.extname(file.originalname),
    );
  },
});

const fileFilter = (req, file, cb) => {
  if (file.fieldname === "catalog_pdf") {
    if (file.mimetype === "application/pdf") {
      return cb(null, true);
    }

    ```
return cb(
  new Error(
    "Only PDF allowed"
  )
);
```;
  }

  const allowed = ["image/jpeg", "image/jpg", "image/png", "image/webp"];

  if (allowed.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error("Only JPG, JPEG, PNG, WEBP allowed"));
  }
};

module.exports = multer({
  storage,
  fileFilter,
});
