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

// =============================================
// Memory Storage
// Image will be processed by Sharp before saving
// =============================================

const storage = multer.memoryStorage();

// =============================================
// File Filter
// Accept only Image Files
// =============================================

const fileFilter = (req, file, cb) => {

    // Allowed Extensions
    const allowedExtensions = [".jpg", ".jpeg", ".png"];

    // Get Extension
    const extension = path.extname(file.originalname).toLowerCase();

    // Check Extension
    const isExtensionValid = allowedExtensions.includes(extension);

    // Check Mime Type
    const isMimeValid = file.mimetype.startsWith("image/");

    if (!isExtensionValid) {

        return cb(
            new Error("Only JPG, JPEG and PNG image files are allowed."),
            false
        );

    }

    if (!isMimeValid) {

        return cb(
            new Error("Invalid image file."),
            false
        );

    }

    cb(null, true);

};

// =============================================
// Multer Configuration
// =============================================

const upload = multer({

    storage,

    fileFilter,

    limits: {

        // 5 MB
        fileSize: 5 * 1024 * 1024,

        // Only one file
        files: 1

    }

});

module.exports = upload;