const multer = require('multer');
const { uploadBuffer, imageKey, videoKey, getPublicUrl } = require('../services/r2');
const path = require('path');

// Store in memory first, then we push to R2 manually
// (multer-s3 has issues with R2's multipart; manual upload is more reliable)
const memoryStorage = multer.memoryStorage();

// ─── Image upload (poster, banner, thumbnail) ────────────────
const imageUpload = multer({
  storage: memoryStorage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB max per image
  fileFilter: (req, file, cb) => {
    const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    if (allowed.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Only JPEG, PNG, and WebP images are allowed'));
    }
  },
});

// ─── Video upload (raw file, no transcoding yet) ─────────────
const videoUpload = multer({
  storage: memoryStorage,
  limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10GB max
  fileFilter: (req, file, cb) => {
    const allowed = ['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska', 'video/webm'];
    if (allowed.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Only MP4, MOV, AVI, MKV, and WebM video files are allowed'));
    }
  },
});

// ─── Movie media upload (poster + banner + video together) ────
const movieMediaUpload = multer({
  storage: memoryStorage,
  limits: { fileSize: 10 * 1024 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const imageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
    const videoTypes = ['video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska', 'video/webm'];
    if ([...imageTypes, ...videoTypes].includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`File type ${file.mimetype} not allowed`));
    }
  },
});

/**
 * Upload a single file buffer to R2 and return { key, url }
 * @param {Express.Multer.File} file
 * @param {string} key - R2 storage key
 */
async function pushToR2(file, key) {
  return uploadBuffer(file.buffer, key, file.mimetype);
}

/**
 * Handle multer errors cleanly
 */
function handleMulterError(err, req, res, next) {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(413).json({ success: false, message: 'File too large' });
    }
    return res.status(400).json({ success: false, message: err.message });
  }
  if (err) {
    return res.status(400).json({ success: false, message: err.message });
  }
  next();
}

module.exports = {
  imageUpload,
  videoUpload,
  movieMediaUpload,
  pushToR2,
  handleMulterError,
};
