const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { BadRequestError } = require('../utils/errors');

// Ensure uploads directory exists
const createUploadsDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// Set up storage engine
const storage = multer.diskStorage({
  destination: function (req, res, file, cb) {
    let uploadPath = 'uploads/';
    
    // Check if this is a pharmacist image upload
    if (req.baseUrl && req.baseUrl.includes('pharmacists')) {
      uploadPath += 'pharmacists';
    } 
    // Handle other upload types
    else if (file.mimetype.startsWith('image/')) {
      uploadPath += 'images';
    } else if (file.mimetype.startsWith('application/')) {
      uploadPath += 'documents';
    } else {
      uploadPath += 'others';
    }
    
    createUploadsDir(uploadPath);
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // Create unique filename
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// File filter
const fileFilter = (req, file, cb) => {
  // Accept images only
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif|webp)$/i)) {
    return cb(new BadRequestError('Only image files are allowed!'), false);
  }
  cb(null, true);
};

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

// Delete file helper
const deleteFile = (filePath) => {
  const fullPath = path.join(__dirname, '../', filePath);
  
  return new Promise((resolve, reject) => {
    fs.unlink(fullPath, (err) => {
      if (err) {
        console.error('Error deleting file:', err);
        reject(new Error('Error deleting file'));
      } else {
        resolve();
      }
    });
  });
};

module.exports = {
  upload,
  deleteFile
};
