module.exports = errorHandlerWithLoggerFactory

function errorHandlerWithLoggerFactory({
  logger,
  getStatusCode = (error, request) => 500,
  fieldExtractor = (error, request) => {},
  getResponse = (error, request) => error,
}) {
  return (error, request, reply) => {
    // Use defualt fastify error handling when error is defaultSchemaErrorFormatter
    if (!!error.validation) {
      return reply.code(400).header('Content-Type', 'application/json').send(error.message)
    }

    const fields = fieldExtractor(error, request)
    logger.error(fields)

    reply
      .code(getStatusCode(error, request))
      .header('Content-Type', 'application/json')
      .send(JSON.stringify(getResponse(error, request)))
  }
}
