const multer = require("multer");

// Configure multer to use memory storage
const storage = multer.memoryStorage();

// File filter for image validation
const fileFilter = (req, file, cb) => {
  // Accept only image files
  const allowedMimeTypes = [
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/gif",
    "image/webp",
  ];

  if (allowedMimeTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(
      new Error(
        "Invalid file type. Only JPG, PNG, GIF, and WebP images are allowed.",
      ),
      false,
    );
  }
};

// Create multer upload instance with size limit (5MB)
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB max file size
  },
  fileFilter: fileFilter,
});

// Error handler middleware for multer
const handleUploadError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === "LIMIT_FILE_SIZE") {
      return res.status(400).json({ msg: "File size exceeds 5MB limit" });
    }
    return res.status(400).json({ msg: err.message });
  } else if (err) {
    return res.status(400).json({ msg: err.message });
  }
  next();
};

module.exports = {
  upload,
  handleUploadError,
};
