const multer = require("multer");
const sharp = require("sharp");
const { MAX_FILE_SIZE_BYTES, MAX_IMAGE_DIMENSION, IMAGE_QUALITY } = require("../config/constants");
const { sendError } = require("../utils/http");

// Configure multer for memory storage (we'll process before saving to DB)
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: MAX_FILE_SIZE_BYTES,
  },
  fileFilter: (req, file, cb) => {
    // Only accept images
    if (file.mimetype.startsWith("image/")) {
      cb(null, true);
    } else {
      cb(new Error("Only image files are allowed"), false);
    }
  },
});

// Middleware to process and compress images
const processImage = async (req, res, next) => {
  if (!req.file) {
    return next();
  }

  try {
    // Compress and resize image using constants
    const processedBuffer = await sharp(req.file.buffer)
      .resize(MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION, {
        fit: "inside",
        withoutEnlargement: true,
      })
      .jpeg({ quality: IMAGE_QUALITY })
      .toBuffer();

    // Attach processed image to request
    req.processedImage = {
      buffer: processedBuffer,
      mimeType: "image/jpeg",
    };

    next();
  } catch (error) {
    sendError(res, 400, `Error processing image: ${error.message}`);
  }
};

module.exports = { upload, processImage };
