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

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

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

const { ObjectId } = require('mongodb');

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

// A1P

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

const ImportaDescrSchema = new Schema({
  idapp: {
    type: String,
  },
  _id: {
    type: String,
  },
  
});

var ImportaDescr = module.exports = mongoose.model('ImportaDescr', ImportaDescrSchema);

ImportaDescrSchema.index({ idapp: 1 });

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

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

module.exports.getImportaDescrByCode = function (idapp, code) {
  return ImportaDescr.findAllIdApp(idapp, code);
}

module.exports.getImportaDescrById = async function (id) {
  const arrris = await ImportaDescr.findAllIdApp('', '', id);
  return arrris && arrris.length > 0 ? arrris[0] : null
}

module.exports.findAllIdApp = async function (idapp) {
  const ImportaDescr = this;

  const myfind = { idapp, deleted: false };

  try {
    return await ImportaDescr.find(myfind).lean();
  } catch (err) {
    console.error("Errore in ImportaDescr:", err);
    return null;
  }
};