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 MyScrapingBookSchema = new Schema({
  isbn: {
    type: String,
    index: true,
  },
  isbn10: {
    type: String,
  },
  fonte: {
    type: String,
  },
  titolo: {
    type: String,
  },
  titoloOriginale: {
    type: String,
  },
  sottotitolo: {
    type: String,
  },
  autore: {
    type: String,
  },
  pagine: {
    type: String,
  },
  misure: {
    type: String,
  },
  edizione: {
    type: String,
  },
  editore: {
    type: String,
  },
  date_pub: {
    type: Date,
  },
  url: {
    type: String,
  },
  stelline: {
    type: Number,
  },
  prezzo: {
    type: String,
  },
  date_extraction: {
    type: Date,
  },
  descrizione_lunga: {
    type: String,  
  },
});

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

MyScrapingBookSchema.statics.executeQueryTable = function (idapp, params, user) {
  params.fieldsearch = this.getFieldsForSearch();
  return tools.executeQueryTable(this, idapp, params, user);
};

MyScrapingBookSchema.statics.findAllIdApp = async function (idapp) {
  const MyScrapingBook = this;

  const myfind = { idapp };

  try {
    return await MyScrapingBook.find(myfind).sort({ titolo: 1 }).lean();
  } catch (err) {
    console.error('Errore in MyScrapingBook:', err, model);
    return null;
  }
};

const MyScrapingBook = mongoose.model('MyScrapingBook', MyScrapingBookSchema);

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

module.exports = { MyScrapingBook };
