const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { BadRequestError } = require('../utils/errors');

/**
 * Create dynamic multer uploader
 * @param {Object} options
 * @param {String} options.folder - subfolder inside /public/uploads
 * @param {String} options.fieldName - form-data field name
 * @param {Number} options.maxSizeMB - max file size in MB
 */
const createUploader = ({
  folder = 'general',
  fieldName = 'file',
  maxSizeMB = 20,
} = {}) => {
  const uploadDir = path.join(process.cwd(), 'public', 'uploads', folder);

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

  // Accept docs + images + logos
  const allowedMimeTypes = [
    // Images
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/webp',
    'image/svg+xml',

    // PDF
    'application/pdf'
  ];

  const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, uploadDir);
    },

    filename: function (req, file, cb) {
      const ext = path.extname(file.originalname || '').toLowerCase();

      const baseName = path
        .basename(file.originalname || 'document', ext)
        .replace(/[^a-zA-Z0-9-_]/g, '_')
        .slice(0, 60);

      const uniqueName = `${Date.now()}-${Math.round(
        Math.random() * 1e9
      )}-${baseName}${ext}`;

      cb(null, uniqueName);
    },
  });

  const fileFilter = (req, file, cb) => {
    if (!allowedMimeTypes.includes(file.mimetype)) {
      return cb(
        new BadRequestError(
          'Only images, logos, PDF, Word, Excel, PowerPoint, CSV, TXT files are allowed'
        ),
        false
      );
    }

    cb(null, true);
  };

  return multer({
    storage,
    fileFilter,
    limits: {
      fileSize: maxSizeMB * 1024 * 1024,
      files: 1,
    },
  }).single(fieldName);
};

module.exports = createUploader;