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

const BASE_UPLOAD_DIR = `/www/wwwroot/upload/`;

try {
  if (!fs.existsSync(BASE_UPLOAD_DIR)) {
    fs.mkdirSync(BASE_UPLOAD_DIR, {recursive: true});
    console.log (`Created upload directory: ${BASE_UPLOAD_DIR}`);
  }
} catch(err) {
  console.error(`Error creating base upload directory ${BASE_UPLOAD_DIR}:`, err.message);
}


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    try {
      const { objectId, fileType, name, model } = req.query;
      if (!objectId || !name || !fileType || !model) {
        return cb(new Error('Required fields missed'));
      }
      const uploadDir = `${BASE_UPLOAD_DIR}${model}/${objectId}/${fileType}/`;
      if (!fs.existsSync(uploadDir)) {
         fs.mkdirSync(uploadDir, {recursive: true});
         console.log (`Created upload directory: ${uploadDir}/`);
      }
      cb(null, uploadDir);
    } catch (err) {
      console.error('Error in upload destination:', err);
      cb(err);
    }
  },
  filename: (req, file, cb) => {
    try {
      const { objectId, fileType, name, date} = req.query;
      const uniqueSuffix = date || Date.now();
      cb(null, `${(name || '').replaceAll(' ', '_')}_${objectId}_${fileType}_${uniqueSuffix}${path.extname(file.originalname)}`)
    } catch (err) {
      console.error('Error in upload filename:', err);
      cb(err);
    }
  }
})
const uploadPhysicalFile = multer({
  storage: storage,
  limits: {fileSize: 10 * 1024* 1024},
  fileFilter: (req, file, cb) => cb(null, true)
}).single('file');

// const memoryStorage = multer.memoryStorage();

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

// const uploadPhysicalFile = (req, res, next) => {
//   upload.single('file')(req, res, async (err) => {
//     if (err) {
//       return res.status(400).send({message: `Uplodad Error: ${err}`});
//     }

//     if (!req.file) {
//       return res.status(400).send({message: 'No File uploaded'});
//     }

//     try {
//       const {objectId, name, fileType} = req.body;
//       if (!objectId || !name || fileType) {
//         return res.status(400).send({message: 'Required fields missed'});
//       }
//       const uploadDir = `${BASE_UPLOAD_DIR}${objectId}/${fileType}/`;
//       if (!fs.existsSync(uploadDir)) {
//         fs.mkdirSync(uploadDir, {recursive: true});
//         console.log (`Created upload directory: ${uploadDir}`);
//       }
//       const uniqueSuffix = Date.now();
//       const fileExension = path.extname(req.file.originalname);
//       const fileName = `${name.replaceAll(' ', '_')}_${objectId}_${fileType}_${uniqueSuffix}${fileExension}`;
//       const filePath = path.join(uploadDir, fileName);

//       fs.writeFileSync(filePath, req.file.buffer);

//       req.fileInfo = {
//         filename: fileName,
//         path: filePath,
//         originalname: req.file.originalname,
//         size: req.file.size
//       };
//       next();

//     } catch (err) {
//       return res.status(500).send({message: `Upload Parsing error: ${err}`});
//     }
//   })
// }


module.exports = uploadPhysicalFile;