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

const {
    validateFileType,
    validateFileSize,
    sanitizeFileName
} = require("./validators");

// ==========================================
// Upload Factory
// ==========================================

function createUpload(options = {}) {

    const {

        destination = "temp",
        maxFileSize = 5 * 1024 * 1024, // 5MB default

    } = options;

    // ======================================
    // Storage Engine
    // ======================================

    const storage = multer.diskStorage({

        destination: function (req, file, cb) {

            const uploadPath = path.join(
                process.cwd(),
                "media",
                destination
            );

            if (!fs.existsSync(uploadPath)) {
                fs.mkdirSync(uploadPath, { recursive: true });
            }

            cb(null, uploadPath);

        },

        filename: function (req, file, cb) {

            const fileName = sanitizeFileName(file.originalname);

            cb(null, fileName);

        }

    });

    // ======================================
    // File Filter
    // ======================================

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

        const typeCheck = validateFileType(file);

        if (!typeCheck.valid) {
            return cb(new Error(typeCheck.message));
        }

        cb(null, true);

    };

    // ======================================
    // Multer Config
    // ======================================

    return multer({

        storage,

        fileFilter,

        limits: {
            fileSize: maxFileSize,
            files: 1
        }

    });

}

module.exports = createUpload;