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

// const ensureDir = (dir) => {
//   if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
// };

// const UPLOAD_BASE = path.join(__dirname, "../uploads");
// const IMAGE_DIR = path.join(UPLOAD_BASE, "images");
// const DOC_DIR = path.join(UPLOAD_BASE, "docs");
// const OTHER_DIR = path.join(UPLOAD_BASE, "others");

// [IMAGE_DIR, DOC_DIR, OTHER_DIR].forEach(ensureDir);

// const storage = multer.diskStorage({
//   destination: (req, file, cb) => {
//     let folder = OTHER_DIR;
//     if (file.mimetype.startsWith("image/")) folder = IMAGE_DIR;
//     else if (
//       file.mimetype === "application/pdf" ||
//       file.mimetype ===
//         "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
//       file.mimetype === "application/vnd.ms-excel"
//     )
//       folder = DOC_DIR;
//     /*  DATE BASED SUBFOLDER */
//     const now = new Date();
//     const year = now.getFullYear().toString();
//     const month = (now.getMonth() + 1).toString().padStart(2, "0");
//     const finalDir = path.join(folder, year, month);
//     ensureDir(finalDir);

//     // cb(null, folder);
//     cb(null, finalDir);
//   },
//   // filename: (req, file, cb) => {
//   //   const ext = path.extname(file.originalname);
//   //   const name = path
//   //     .basename(file.originalname, ext)
//   //     .replace(/\s+/g, "_")
//   //     .replace(/[^\w\-]/g, "");
//   //   cb(null, `${name}-${Date.now()}${ext}`);
//   // },
//   //   filename: (req, file, cb) => {
//   //   const ext = path.extname(file.originalname);
//   //   const safeName = path
//   //     .basename(file.originalname, ext)
//   //     .replace(/\s+/g, "_")
//   //     .replace(/[^\w\-]/g, "");

//   //   const uniqueId = crypto.randomUUID();

//   //   cb(null, `${safeName}-${Date.now()}-${uniqueId}${ext}`);
//   // },

//   // filename: (req, file, cb) => {
//   //   const ext = path.extname(file.originalname);
//   //   const shortId = crypto.randomBytes(4).toString("hex"); // 8 chars
//   //   cb(null, `${Date.now()}-${shortId}${ext}`);
//   // },

//   filename: (req, file, cb) => {
//     let ext = path.extname(file.originalname);

//     //  Fallback if extension is missing or invalid
//     if (!ext) {
//       const mimeMap = {
//         "image/jpeg": ".jpg",
//         "image/png": ".png",
//         "image/gif": ".gif",
//         "application/pdf": ".pdf",
//       };
//       ext = mimeMap[file.mimetype] || "";
//     }

//     const shortId = crypto.randomBytes(4).toString("hex");
//     cb(null, `${Date.now()}-${shortId}${ext}`);
//   },
// });

// const fileFilter = (req, file, cb) => {
//   const allowedMimeTypes = [
//     "image/jpeg",
//     "image/png",
//     "image/gif",
//     "application/pdf",
//     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
//     "application/vnd.ms-excel",
//   ];
//   if (allowedMimeTypes.includes(file.mimetype)) cb(null, true);
//   else
//     cb(
//       new Error(
//         "Invalid file type! Only images, PDFs, and Excel files are allowed.",
//       ),
//       false,
//     );
// };

// const upload = multer({
//   storage,
//   fileFilter,
//   limits: { fileSize: 5 * 1024 * 1024 },
// });

// module.exports = upload;


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

const ensureDir = (dir) => {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
};

const UPLOAD_BASE = path.join(__dirname, "../uploads");
const IMAGE_DIR = path.join(UPLOAD_BASE, "images");
const DOC_DIR = path.join(UPLOAD_BASE, "docs");
const OTHER_DIR = path.join(UPLOAD_BASE, "others");

[IMAGE_DIR, DOC_DIR, OTHER_DIR].forEach(ensureDir);

// For files that need to be saved to disk (images, regular docs)
const diskStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    let folder = OTHER_DIR;
    if (file.mimetype.startsWith("image/")) folder = IMAGE_DIR;
    else if (
      file.mimetype === "application/pdf" ||
      file.mimetype ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      file.mimetype === "application/vnd.ms-excel"
    )
      folder = DOC_DIR;
    
    const now = new Date();
    const year = now.getFullYear().toString();
    const month = (now.getMonth() + 1).toString().padStart(2, "0");
    const finalDir = path.join(folder, year, month);
    ensureDir(finalDir);

    cb(null, finalDir);
  },
  filename: (req, file, cb) => {
    let ext = path.extname(file.originalname);
    if (!ext) {
      const mimeMap = {
        "image/jpeg": ".jpg",
        "image/png": ".png",
        "image/gif": ".gif",
        "application/pdf": ".pdf",
      };
      ext = mimeMap[file.mimetype] || "";
    }
    const shortId = crypto.randomBytes(4).toString("hex");
    cb(null, `${Date.now()}-${shortId}${ext}`);
  },
});

// For Excel files that need to be parsed in memory (bulk upload)
const memoryStorage = multer.memoryStorage();

// File filter for all uploads
const fileFilter = (req, file, cb) => {
  console.log("MIME:", file.mimetype);
  console.log("EXT:", path.extname(file.originalname));
  const allowedMimeTypes = [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/jpg",
     "image/svg+xml",
    "application/pdf",
    "application/octet-stream",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel",
    "text/csv",
    "application/csv"
  ];
  if (allowedMimeTypes.includes(file.mimetype)) cb(null, true);
  else
    cb(
      new Error(
        "Invalid file type! Only images, PDFs, Excel, and CSV files are allowed.",
      ),
      false,
    );
};

// Create main upload instance (for disk storage - backward compatible)
const upload = multer({
  storage: diskStorage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 },
});

// Create bulk upload instance (for memory storage)
const uploadForBulk = multer({
  storage: memoryStorage,
  fileFilter: (req, file, cb) => {
    const allowedMimeTypes = [
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "application/vnd.ms-excel",
      "text/csv",
      "application/csv"
    ];
    if (allowedMimeTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error("Invalid file type! Only Excel and CSV files are allowed."), false);
    }
  },
  limits: { fileSize: 5 * 1024 * 1024 },
});

// Attach methods to upload instance for backward compatibility
upload.single = upload.single.bind(upload);
upload.array = upload.array.bind(upload);
upload.fields = upload.fields.bind(upload);
upload.none = upload.none.bind(upload);

// Add bulk upload instance as a property
upload.uploadForBulk = uploadForBulk;

// Export the main upload instance
module.exports = upload;