import { getOrSetGlobal } from '@warp-drive/core-types/-private';
import { macroCondition, getGlobalConfig } from '@embroider/macros';
function _AdapterError(errors, message = 'Adapter operation failed') {
  this.isAdapterError = true;
  const error = Error.call(this, message);
  if (error) {
    this.stack = error.stack;
    this.description = error.description;
    this.fileName = error.fileName;
    this.lineNumber = error.lineNumber;
    this.message = error.message;
    this.name = error.name;
    this.number = error.number;
  }
  this.errors = errors || [{
    title: 'Adapter Error',
    detail: message
  }];
}
_AdapterError.prototype = Object.create(Error.prototype);
_AdapterError.prototype.code = 'AdapterError';
_AdapterError.extend = extendFn(_AdapterError);
const AdapterError = getOrSetGlobal('AdapterError', _AdapterError);
function extendFn(ErrorClass) {
  return function ({
    message: defaultMessage
  } = {}) {
    return extend(ErrorClass, defaultMessage);
  };
}
function extend(ParentErrorClass, defaultMessage) {
  const ErrorClass = function (errors, message) {
    macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
      if (!test) {
        throw new Error('`AdapterError` expects json-api formatted errors array.');
      }
    })(Array.isArray(errors || [])) : {};
    ParentErrorClass.call(this, errors, message || defaultMessage);
  };
  ErrorClass.prototype = Object.create(ParentErrorClass.prototype);
  ErrorClass.extend = extendFn(ErrorClass);
  return ErrorClass;
}

/**
  A `InvalidError` is used by an adapter to signal the external API
  was unable to process a request because the content was not
  semantically correct or meaningful per the API. Usually, this means a
  record failed some form of server-side validation. When a promise
  from an adapter is rejected with a `InvalidError` the record will
  transition to the `invalid` state and the errors will be set to the
  `errors` property on the record.

  For Ember Data to correctly map errors to their corresponding
  properties on the model, Ember Data expects each error to be
  a valid JSON-API error object with a `source/pointer` that matches
  the property name. For example, if you had a Post model that
  looked like this.

  ```js [app/models/post.js]
  import Model, { attr } from '@ember-data/model';

  export default class PostModel extends Model {
    @attr('string') title;
    @attr('string') content;
  }
  ```

  To show an error from the server related to the `title` and
  `content` properties your adapter could return a promise that
  rejects with a `InvalidError` object that looks like this:

  ```js [app/adapters/post.js]
  import RSVP from 'RSVP';
  import RESTAdapter from '@ember-data/adapter/rest';
  import { InvalidError } from '@ember-data/adapter/error';

  export default class ApplicationAdapter extends RESTAdapter {
    updateRecord() {
      // Fictional adapter that always rejects
      return RSVP.reject(new InvalidError([
        {
          detail: 'Must be unique',
          source: { pointer: '/data/attributes/title' }
        },
        {
          detail: 'Must not be blank',
          source: { pointer: '/data/attributes/content'}
        }
      ]));
    }
  }
  ```

  Your backend may use different property names for your records the
  store will attempt to extract and normalize the errors using the
  serializer's `extractErrors` method before the errors get added to
  the model. As a result, it is safe for the `InvalidError` to
  wrap the error payload unaltered.

  @class InvalidError
  @public
*/
// TODO @deprecate extractError documentation
const InvalidError = getOrSetGlobal('InvalidError', extend(AdapterError, 'The adapter rejected the commit because it was invalid'));
InvalidError.prototype.code = 'InvalidError';

/**
  A `TimeoutError` is used by an adapter to signal that a request
  to the external API has timed out. I.e. no response was received from
  the external API within an allowed time period.

  An example use case would be to warn the user to check their internet
  connection if an adapter operation has timed out:

  ```js [app/routes/application.js]
  import { TimeoutError } from '@ember-data/adapter/error';

  export default class ApplicationRoute extends Route {
    @action
    error(error, transition) {
      if (error instanceof TimeoutError) {
        // alert the user
        alert('Are you still connected to the Internet?');
        return;
      }

      // ...other error handling logic
    }
  }
  ```

  @class TimeoutError
  @public
*/
const TimeoutError = getOrSetGlobal('TimeoutError', extend(AdapterError, 'The adapter operation timed out'));
TimeoutError.prototype.code = 'TimeoutError';

/**
  A `AbortError` is used by an adapter to signal that a request to
  the external API was aborted. For example, this can occur if the user
  navigates away from the current page after a request to the external API
  has been initiated but before a response has been received.

  @class AbortError
  @public
*/
const AbortError = getOrSetGlobal('AbortError', extend(AdapterError, 'The adapter operation was aborted'));
AbortError.prototype.code = 'AbortError';

/**
  A `UnauthorizedError` equates to a HTTP `401 Unauthorized` response
  status. It is used by an adapter to signal that a request to the external
  API was rejected because authorization is required and has failed or has not
  yet been provided.

  An example use case would be to redirect the user to a login route if a
  request is unauthorized:

  ```js [app/routes/application.js]
  import { UnauthorizedError } from '@ember-data/adapter/error';

  export default class ApplicationRoute extends Route {
    @action
    error(error, transition) {
      if (error instanceof UnauthorizedError) {
        // go to the login route
        this.transitionTo('login');
        return;
      }

      // ...other error handling logic
    }
  }
  ```

  @class UnauthorizedError
  @public
*/
const UnauthorizedError = getOrSetGlobal('UnauthorizedError', extend(AdapterError, 'The adapter operation is unauthorized'));
UnauthorizedError.prototype.code = 'UnauthorizedError';

/**
  A `ForbiddenError` equates to a HTTP `403 Forbidden` response status.
  It is used by an adapter to signal that a request to the external API was
  valid but the server is refusing to respond to it. If authorization was
  provided and is valid, then the authenticated user does not have the
  necessary permissions for the request.

  @class ForbiddenError
  @public
*/
const ForbiddenError = getOrSetGlobal('ForbiddenError', extend(AdapterError, 'The adapter operation is forbidden'));
ForbiddenError.prototype.code = 'ForbiddenError';

/**
  A `NotFoundError` equates to a HTTP `404 Not Found` response status.
  It is used by an adapter to signal that a request to the external API
  was rejected because the resource could not be found on the API.

  An example use case would be to detect if the user has entered a route
  for a specific model that does not exist. For example:

  ```js [app/routes/post.js]
  import { NotFoundError } from '@ember-data/adapter/error';

  export default class PostRoute extends Route {
    @service store;
    model(params) {
      return this.store.findRecord('post', params.post_id);
    }
    @action
    error(error, transition) {
      if (error instanceof NotFoundError) {
        // redirect to a list of all posts instead
        this.transitionTo('posts');
      } else {
        // otherwise let the error bubble
        return true;
      }
    }
  }
  ```

  @class NotFoundError
  @public
*/
const NotFoundError = getOrSetGlobal('NotFoundError', extend(AdapterError, 'The adapter could not find the resource'));
NotFoundError.prototype.code = 'NotFoundError';

/**
  A `ConflictError` equates to a HTTP `409 Conflict` response status.
  It is used by an adapter to indicate that the request could not be processed
  because of a conflict in the request. An example scenario would be when
  creating a record with a client-generated ID but that ID is already known
  to the external API.

  @class ConflictError
  @public
*/
const ConflictError = getOrSetGlobal('ConflictError', extend(AdapterError, 'The adapter operation failed due to a conflict'));
ConflictError.prototype.code = 'ConflictError';

/**
  A `ServerError` equates to a HTTP `500 Internal Server Error` response
  status. It is used by the adapter to indicate that a request has failed
  because of an error in the external API.

  @class ServerError
  @public
*/
const ServerError = getOrSetGlobal('ServerError', extend(AdapterError, 'The adapter operation failed due to a server error'));
ServerError.prototype.code = 'ServerError';
export { AbortError, ConflictError, ForbiddenError, InvalidError, NotFoundError, ServerError, TimeoutError, UnauthorizedError, AdapterError as default };