const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');

class UploadMiddleware {
  constructor(baseUploadPath = 'uploads/videos') {
    this.baseUploadPath = path.resolve(baseUploadPath);
    this._ensureDirectory(this.baseUploadPath);
  }

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

  _createStorage() {
    return multer.diskStorage({
      destination: (req, file, cb) => {
        // ✅ Legge SOLO da req.query (affidabile con multer)
        const folder = req.query.folder || 'default';
        
        console.log('📁 Upload folder:', folder); // Debug
        
        const uploadPath = path.join(this.baseUploadPath, folder);
        this._ensureDirectory(uploadPath);
        cb(null, uploadPath);
      },
      filename: (req, file, cb) => {
        const ext = path.extname(file.originalname);
        const uniqueName = `${uuidv4()}-${Date.now()}${ext}`;
        cb(null, uniqueName);
      }
    });
  }

  _fileFilter(req, file, cb) {
    const allowedMimes = [
      'video/mp4',
      'video/webm',
      'video/ogg',
      'video/quicktime',
      'video/x-msvideo',
      'video/x-matroska'
    ];

    if (allowedMimes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`Tipo file non supportato: ${file.mimetype}`), false);
    }
  }

  getUploader(options = {}) {
    const config = {
      storage: this._createStorage(),
      fileFilter: this._fileFilter.bind(this),
      limits: {
        fileSize: options.maxSize || 500 * 1024 * 1024,
        files: options.maxFiles || 10
      }
    };

    return multer(config);
  }

  single(fieldName = 'video') {
    return this.getUploader().single(fieldName);
  }

  multiple(fieldName = 'videos', maxCount = 10) {
    return this.getUploader({ maxFiles: maxCount }).array(fieldName, maxCount);
  }

  getBasePath() {
    return this.baseUploadPath;
  }
}

module.exports = UploadMiddleware;