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

const storage = multer.memoryStorage();

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

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

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

    const isExtensionValid =
        allowedExtensions.includes(extension);

    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);

};

const uploadTraining = multer({

    storage,

    fileFilter,

    limits: {

        fileSize: 5 * 1024 * 1024,

        files: 10

    }

});

module.exports = uploadTraining;