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

const EXCEL_DIR = path.join(__dirname, "../uploads/excel");
if (!fs.existsSync(EXCEL_DIR)) fs.mkdirSync(EXCEL_DIR, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, EXCEL_DIR),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const name = path.basename(file.originalname, ext);
    cb(null, `${name}-${Date.now()}${ext}`);
  },
});

// const excelFileFilter = (req, file, cb) => {
//   const allowedExt = [".xlsx", ".xls"];
//   const allowedMime = [
//     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
//     "application/vnd.ms-excel",
//     "application/octet-stream", // 👈 important for browsers
//   ];

//   const ext = path.extname(file.originalname).toLowerCase();

//   if (allowedExt.includes(ext) || allowedMime.includes(file.mimetype)) {
//     cb(null, true);
//   } else {
//     cb(new Error("Only Excel files (.xlsx, .xls) are allowed"), false);
//   }
// };
const excelFileFilter = (req, file, cb) => {
  const ext = path.extname(file.originalname).toLowerCase();

  // ✅ Trust extension first (industry standard)
  if (ext === ".xlsx" || ext === ".xls") {
    return cb(null, true);
  }

  return cb(
    new Error("Only Excel files (.xlsx, .xls) are allowed"),
    false
  );
};


module.exports = multer({
  storage,
  fileFilter: excelFileFilter,
  limits: { fileSize: 20 * 1024 * 1024 }, // 20MB for bulk upload
});
