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

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

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


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

const ListaInvitiEmailSchema = new Schema({
  idapp: {
    type: String,
  },
  email: {
    type: String,
    trim: true,
  },
  userIdInvite: {
    type: String,
  },
  usernameInvitante: {
    type: String,
  },
  date_Invited: {
    type: Date,
    default: Date.now,
  },
  clicked: {
    type: Boolean,
    default: false,
  },
  registered: {
    type: Boolean,
    default: false,
  },
  userIdRegistered: {
    type: String,
  },
  token: {
    type: String,
  },
});

var ListaInvitiEmail = module.exports = mongoose.model('ListaInvitiEmail', ListaInvitiEmailSchema);

module.exports.getFieldsForSearch = function () {
  return [{ field: 'email', type: tools.FieldType.string }]
};



module.exports.executeQueryTable = function (idapp, params) {
  params.fieldsearch = this.getFieldsForSearch();
  return tools.executeQueryTable(this, idapp, params);
};

module.exports.getLastRec = async function (idapp) {
  const lastrec = await ListaInvitiEmail.find({ idapp }).sort({ dateofreg: -1 }).limit(1);
  if (!!lastrec) {
    return lastrec[0];
  } else {
    return null;
  }
};

module.exports.findByEmail = function (idapp, email) {

  return ListaInvitiEmail.findOne({
    'idapp': idapp,
    'email': email,
  });
};


module.exports.findAllIdApp = async function (idapp) {

  const myfind = { idapp };

  return await tools.findAllQueryIdApp(this, myfind);
};

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