text: const AppError = require("../helpers/appError");
  
  const sendDevError = (err, req, res) => {
      const { status, message, stack } = err;
  
      console.log(`DEV ERROR: ${err}`);
  
      res.status(err.statusCode).json({
          status,
          message,
          error: err,
          stack
      });
  };
  
  const sendProdError = (err, req, res) => {
      const { status, message } = err;
  
      console.log(`PRODUCTION ERROR: ${err}`);
      res.status(err.statusCode).json({
          status,
          message
      });
  };
  
  const castErrorHandlerDB = err => {
      const message = `Invalid ${err.path} : ${err.value}`;
      return new AppError(message, 400);
  };
  
  const handleValidationErrorDB = err => {
      const errors = Object.values(err.errors).map(el => el.message);
      const message = `Invalid Data: ${errors.join(" ")}`;
      return new AppError(message, 400);
  };
  
  const handleDuplicationErrorDB = err => {
      const value = err.message.match(/(["'])(?:(?=(\\?))\2.)*?\1/)[0];
      const message = `Email address is already taken ${value}. Please use another value.`;
  
      return new AppError(message, 400);
  };
  
  const handleJWTError = () =>
      new AppError("Invalid JWT Token. Please login again!.", 401);
  
  const handleJWTExpireError = () =>
      new AppError("JWT Token expired. Please login to access", 401);
  
  module.exports = (err, req, res, next) => {
      err.statusCode = err.statusCode || 500;
      err.status = err.status || "error";
  
      if (process.env.Node_ENV === "development") {
          let error = Object.assign(err);
          if (error.name === "CastError") error = castErrorHandlerDB(error);
          if (error.name === "ValidationError")
              error = handleValidationErrorDB(error);
          if (error.code === 11000) error = handleDuplicationErrorDB(error);
          if (error.name === "JsonWebTokenError") error = handleJWTError();
          if (error.name === "TokenExpiredError") error = handleJWTExpireError();
          sendDevError(error, req, res);
      } else {
          sendProdError(err, req, res);
      }
  };
  