const { SERVER_ERROR } = require("./errorMessage");
const { STATUS_CODE } = require("./utility");

class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.status = false;
    this.isAppError = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

module.exports = AppError;

module.exports.sendAppError = (extras, message, statusCode) => {
  if (extras.transaction) {
    return extras.transaction?.rollback().finally(() => extras.next(new AppError(message, statusCode)));
  }
  else {
    return extras.next(new AppError(message, statusCode));
  }
}

module.exports.sendInternalServerError = (extras) => {
  if (extras.transaction) {
    return extras.transaction?.rollback().finally(() => extras.next(new AppError(SERVER_ERROR, STATUS_CODE.INTERNAL_SERVER_ERROR)));
  }
  else {
    return extras.next(new AppError(SERVER_ERROR, STATUS_CODE.INTERNAL_SERVER_ERROR));
  }
}