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

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const folder = file.fieldname === 'profile_photo' ? 'profiles' : 'reports';
    cb(null, path.join(__dirname, '../uploads/', folder));
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const name = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`;
    cb(null, name);
  },
});

const fileFilter = (req, file, cb) => {
  const allowed = ['image/jpeg', 'image/png', 'image/webp'];
  if (allowed.includes(file.mimetype)) cb(null, true);
  else cb(new Error('Only JPEG, PNG, and WebP images are allowed'), false);
};

const uploadProfile = multer({ storage, fileFilter, limits: { fileSize: 5 * 1024 * 1024 } }).single('profile_photo');
const uploadReportPhotos = multer({ storage, fileFilter, limits: { fileSize: 5 * 1024 * 1024 } }).fields([
  { name: 'photo_1', maxCount: 1 },
  { name: 'photo_2', maxCount: 1 },
]);

module.exports = { uploadProfile, uploadReportPhotos };
