const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;

const tools = require('../tools/general');

const shared_consts = require('../tools/shared_nodejs');

mongoose.Promise = global.Promise;
mongoose.level = 'F';

// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
  schema.options.usePushEach = true;
});

const UserRequestSchema = new Schema({
  _id: {
    type: Number,
  },
  idapp: {
    type: String,
  },
  typeReq: {
    type: Number,
  },
  valueRequested: {
    type: Number,
  },
  strRequested: {
    type: String,
  },
  username: {
    type: String,
  },
  groupname: {
    type: String,
  },
  note: {
    type: String,
  },
  createdBy: {
    type: String,
  },
  date_created: {
    type: Date,
  },
  date_updated: {
    type: Date,
  },
  deleted: {
    type: Boolean,
    default: false,
  },
  processed: {
    type: Boolean,
    default: false,
  },
  username_answered: {
    type: String,
  },
  state_requested: {
    type: Number,
  },
  msgout_answered: {
    type: String,
  },
});

UserRequestSchema.statics.getFieldsForSearch = function () {
  return [{ field: 'descr', type: tools.FieldType.string }];
};

UserRequestSchema.statics.executeQueryTable = function (idapp, params, user) {
  params.fieldsearch = this.getFieldsForSearch();

  const { User } = require('./user');

  return tools.executeQueryTable(this, idapp, params, user);
};

UserRequestSchema.pre('save', async function (next) {
  if (this.isNew) {
    this.date_created = new Date();
  }

  next();
});

UserRequestSchema.statics.findAllIdApp = async function (idapp) {
  const myfind = { idapp };

  return await UserRequest.find(myfind);
};


const UserRequest = mongoose.model('UserRequest', UserRequestSchema);

UserRequest.createIndexes()
  .then(() => { })
  .catch((err) => { throw err; });


module.exports = { UserRequest };
