// File: uploadMiddleware.js
const fs = require("fs");
const multer = require("multer");
const path = require("path");

const uploadsDir = path.join(__dirname, "../uploads");
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir);
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = Date.now() + path.extname(file.originalname);
    cb(null, uniqueName);
  },
});

const fileFilter = (req, file, cb) => {
  const allowedFileTypes = /\.(jpg|jpeg|png|gif)$/i;
  if (!allowedFileTypes.test(file.originalname)) {
    req.fileValidationError = "Only image files are allowed!";
    return cb(new Error("Only image files are allowed!"), false);
  }
  cb(null, true);
};

// Multer upload configuration
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB file size limit
  },
  fileFilter: fileFilter,
});

const multerErrorHandler = (error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    let errorMessage = "An error occurred during file upload.";
    if (error.code === "LIMIT_FILE_SIZE") {
      errorMessage = "File size is too large. Maximum size is 5MB.";
    }
    return res.status(400).json({ success: false, message: errorMessage });
  }

  if (error.message === "Only image files are allowed!") {
    return res.status(400).json({ success: false, message: error.message });
  }

  next(error);
};

module.exports = { upload, multerErrorHandler };
