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

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

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

// const CatAI = require('./catai');

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

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

const OpenAI = require("openai");

const QueryAISchema = new Schema({
  idapp: {
    type: String,
  },
  descr: {
    type: String,
  },
  catAI: { type: Schema.Types.ObjectId, ref: 'CatAI' },
  query: {
    type: String,
  },
  ask: [
    {
      descr: {
        type: String,
      },
      value: {
        type: Number,
      },
    }
  ],
  buttons: [
    {
      type: String,  //ButtonCodeAction
    },
  ],
  output_type: {
    type: String,
  },
  icon: {
    type: String,
  },
  img: {
    type: String,
  },
});

QueryAISchema.statics.findAllIdApp = async function (idapp) {
  const QueryAI = this;

  const query = [
    { $sort: { descr: 1 } }
  ];

  return await QueryAI
    .aggregate(query)
    .then((arrrec) => {
      return arrrec
    })

};

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

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


const QueryAI = mongoose.model('QueryAI', QueryAISchema);

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


module.exports = { QueryAI };
