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

// Define storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../uploads/audio');
    
    // Create directory if it does not exist
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    // Unique name using timestamp + original name (replacing spaces with hyphens)
    const uniqueSuffix = Date.now() + '-' + file.originalname.replace(/\s+/g, '-');
    cb(null, uniqueSuffix);
  }
});

// File filter to allow only MP3 files
const fileFilter = (req, file, cb) => {
  const allowedExtensions = ['.mp3'];
  const ext = path.extname(file.originalname).toLowerCase();
  
  if (allowedExtensions.includes(ext) || file.mimetype === 'audio/mpeg') {
    cb(null, true);
  } else {
    cb(new Error('Only MP3 files are allowed.'), false);
  }
};

// Initialize multer upload object
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 25 * 1024 * 1024 // Limit file size to 25MB
  }
});

module.exports = upload;
