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

/**
 * Factory: creates a multer instance for the given sub-folder inside `uploads/`.
 * Files are named with a timestamp prefix to avoid collisions.
 *
 * Usage:
 *   const upload = require('../middlewares/upload')('products');
 *   router.post('/', upload.single('image'), ctrl.create);
 */
module.exports = function createUploader(subFolder) {
  // uploads directory moved inside backend/src/uploads
  const dest = path.join(__dirname, '..', 'uploads', subFolder);

  // Ensure directory exists
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const storage = multer.diskStorage({
    destination: (_req, _file, cb) => cb(null, dest),
    filename: (_req, file, cb) => {
      const unique = Date.now() + '-' + Math.round(Math.random() * 1e6);
      const ext = path.extname(file.originalname);
      cb(null, `${unique}${ext}`);
    },
  });

  const fileFilter = (_req, file, cb) => {
    const allowed = /jpeg|jpg|png|gif|webp/;
    const extOk = allowed.test(path.extname(file.originalname).toLowerCase());
    const mimeOk = allowed.test(file.mimetype.split('/')[1]);
    if (extOk && mimeOk) {
      cb(null, true);
    } else {
      cb(new Error('Only image files (jpg, png, gif, webp) are allowed'), false);
    }
  };

  return multer({
    storage,
    fileFilter,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB
  });
};
