const {failure} = require('../utils/apiResponse');

function notFound(req, res) {
  return failure(res, 404, `Route not found: ${req.method} ${req.originalUrl}`);
}

function errorHandler(error, req, res, next) {
  if (res.headersSent) {
    return next(error);
  }

  const statusCode = error.statusCode || error.status || 500;
  const message = statusCode === 500 ? 'Internal server error' : error.message;

  if (process.env.NODE_ENV !== 'test') {
    console.error(error);
  }

  return failure(res, statusCode, message);
}

module.exports = {errorHandler, notFound};
