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

// Configure storage settings
const storage = multer.diskStorage({
  // Directory to store uploaded files
  destination: function (req, file, cb) {
    cb(null, 'backend/uploads/'); // Use the "uploads" folder
  },
  // Generate a unique name for the file
  filename: function (req, file, cb) {
    // Use current date and original file name
    cb(null, Date.now() + '-' + file.originalname);
  }
});

// File filter function to accept only images
const fileFilter = (req, file, cb) => {
  const allowedFileTypes = /jpeg|jpg|png/;
  const extname = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedFileTypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images Only!');
  }
};

// Initialize multer with storage and file filter options
const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 5 }, // 5MB file size limit
  fileFilter: fileFilter
});

module.exports = upload;
