"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildResponse = exports.ResponseFactory = void 0;
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const statusToErrorMessage = statusCode => {
  switch (statusCode) {
    case 400:
      return 'Bad Request';
    case 401:
      return 'Unauthorized';
    case 403:
      return 'Forbidden';
    case 404:
      return 'Not Found';
    case 409:
      return 'Conflict';
    case 500:
      return 'Internal Error';
    default:
      return '(unknown error)';
  }
};

/** Creates responses */
class ResponseFactory {
  /** constructor */
  constructor(response) {
    this.response = response;
  }

  /** error */
  error({
    statusCode,
    body,
    headers
  }) {
    const contentType = {
      'content-type': 'application/json'
    };
    const defaultedHeaders = {
      ...contentType,
      ...(headers !== null && headers !== void 0 ? headers : {})
    };
    return this.response.custom({
      body: Buffer.from(JSON.stringify({
        message: body !== null && body !== void 0 ? body : statusToErrorMessage(statusCode),
        status_code: statusCode
      })),
      headers: defaultedHeaders,
      statusCode
    });
  }
}

/** builds a response */
exports.ResponseFactory = ResponseFactory;
const buildResponse = response => new ResponseFactory(response);
exports.buildResponse = buildResponse;