import multer from "multer";
import fs from "fs";
import path from "path";

const ensureDir = (folderPath) => {
    if (!fs.existsSync(folderPath)) {
        fs.mkdirSync(folderPath, { recursive: true });
    }
};

/**
 * makeUpLoader(folderName, fieldName = "image", mode = "single", maxCount = 10)
 * 
 * - "single" → upload one file (default)
 * - "array" → upload multiple files for same field
 * - "any" → upload any files from any fields
 */
export const makeUpLoader = (
    folderName,
    fieldName = "image",
    mode = "single",
    maxCount = 10
) => {
    const folderPath = path.join("uploads", folderName);
    ensureDir(folderPath);

    const storage = multer.diskStorage({
        destination: (req, file, cb) => cb(null, folderPath),
        filename: (req, file, cb) => {
            const unique = Date.now() + "-" + Math.round(Math.random() * 1e9);
            cb(null, unique + "-" + file.originalname);
        },
    });

    const fileFilter = (req, file, cb) => {
        if (file.mimetype.startsWith("image/")) cb(null, true);
        else cb(new Error("Only image files are allowed!"), false);
    };

    const upload = multer({
        storage,
        fileFilter,
        limits: { fileSize: 2 * 1024 * 1024 }, // 2MB
    });

    const uploadMiddleware =
        mode === "array"
            ? upload.array(fieldName, maxCount)
            : mode === "any"
                ? upload.any()
                : upload.single(fieldName);

    return (req, res, next) => {
        uploadMiddleware(req, res, (err) => {
            if (err instanceof multer.MulterError && err.code === "LIMIT_FILE_SIZE") {
                return res.status(400).json({ message: "File size exceeds 2MB limit" });
            } else if (err) {
                return res.status(400).json({ message: err.message });
            }
            next();
        });
    };
};
