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

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置本地存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = `${Date.now()}-${Math.random().toString(36).substring(7)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 50 * 1024 * 1024 }, // 50MB
  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('只允许上传图片或视频文件'));
  }
});

// 返回文件访问URL
const getFileUrls = (files) => {
  const list = Array.isArray(files) ? files : [files];
  return list.map(file => ({
    url: `/uploads/${file.filename}`,
    filename: file.filename,
    mimetype: file.mimetype
  }));
};

module.exports = { upload, getFileUrls };
