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

const uploadDir = path.join(__dirname, '../storage/posts');
fs.ensureDirSync(uploadDir); // مطمئن میشه مسیر وجود داره

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const name = file.originalname.replace(ext, '').replace(/\s/g, '_');
    cb(null, `${Date.now()}-${name}${ext}`);
  }
});

const fileFilter = (req, file, cb) => {
  if (!file.mimetype.startsWith('image/')) return cb(new Error('فقط تصاویر مجاز است'));
  cb(null, true);
};

const upload = multer({ storage, fileFilter, limits: { files: 10 } }); // حداکثر ۱۰ فایل

module.exports = upload;
