/*
  Catch Errors Handler

  With async/await, you need some way to catch errors
  Instead of using try{} catch(e) {} in each controller, we wrap the function in
  catchErrors(), catch any errors they throw, and pass it along to our express middleware with next()
*/

exports.catchErrors = (fn) => {
  return function (req, res, next) {
    const resp = fn(req, res, next);
    
    
    
    if (resp instanceof Promise) {
      
      return resp.catch(next);
    }
    return resp;
  };
};

/*
  Not Found Error Handler

  If we hit a route that is not found, we mark it as 404 and pass it along to the next error handler to display
*/
exports.notFound = (req, res, next) => {
  res.status(404).json({
    success: false,
    message: "Api url doesn't exist!!! ",
  });
};

/*
  Development Error Handler

  In development we show good error messages so if we hit a syntax error or any other previously un-handled error, we can show good info on what happened
*/
exports.developmentErrors = (err, req, res, next) => {
  err.stack = err.stack || "";
  const errorDetails = {
    message: err.message,
    status: err.status,
    stackHighlighted: err.stack.replace(
      /[a-z_-\d]+.js:\d+:\d+/gi,
      "<mark>$&</mark>"
    ),
  };

  res.status(500).json({
    success: false,
    message: "Oops ! Error in Server dev",
  });
};

/*
  Production Error Handler

  No stacktraces are leaked to admin
*/ 
exports.productionErrors = (err, req, res, next) => {
  const key = req.body.key;
    const token = req.body.token;
    //console.log(process.env.APP_API_KEY);
    if(key != process.env.APP_API_KEY && token != process.env.APP_API_TOKEN){
      //console.log(process.env.APP_API_KEY);
      res.status(500).json({ 
        success: false,
        message: err+" Oops ! Error in Server proddbfdgmngb ", 
      });
    }
  //console.log(err);return false;    
  res.status(500).json({ 
    success: false,
    message: err+" Oops ! Error in Server prod ", 
  });
};

// exports.checkToken = (fn) => {
  
    
//   return function (req, res, next) {
//     const token = req.body.access_token;
    
//     const resp = fn(req, res, next);
//     if (token === process.env.TOKEN_SECRET) {
//       console.log(113);
//       return resp.catch(next);
//     } else {
//       console.log(456);
//       return res.status(404).json({
//         success: false,
//         message: "Token not found!!! ",
//       });
//     }
//   };
// };

exports.checkToken = async (req, res, next) => {
    const token = req.body.access_token;

    // console.log(req.body); 

    if (token === process.env.TOKEN_SECRET) {
      // console.log(113);
      next();
    } else {
      // console.log(456);
      res.status(404).json({
        success: false,
        message: "Token not found!!! ",
      });
    }
    
};