const multer = require('multer');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { uploadBuffer } = require('../utils/minio');

// 使用内存存储，文件不落盘，不限制大小
const upload = multer({
  storage: multer.memoryStorage(),
  fileFilter: (req, file, cb) => {
    const extname = /jpeg|jpg|png|gif|mp4|mov|avi/.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimetype = /image|video/.test(file.mimetype);
    if (mimetype && extname) return cb(null, true);
    cb(new Error('只允许上传图片或视频文件'));
  }
});

// 将 req.files 或 req.file 上传到 MinIO，返回 url 数组或单个 url
const uploadFilesToMinio = async (files) => {
  const list = Array.isArray(files) ? files : [files];
  return Promise.all(list.map(async (file) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const filename = `${Date.now()}-${uuidv4()}${ext}`;
    const url = await uploadBuffer(file.buffer, filename, file.mimetype);
    return { ...file, filename, url };
  }));
};

module.exports = { upload, uploadFilesToMinio };
