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 CollanaSchema = new Schema({
  idapp: {
    type: String,
  },
  idCollana: {
    type: Number,
  },
  title: {
    type: String,
    index: true,
  },
  dataOra: {
    type: Date,
  },
  enabled: {
    type: Boolean,
  },
  enabledAlFresco: {
    type: Boolean,
  },
  quanti: {
    type: Number,
  },

});

var Collana = module.exports = mongoose.model('Collana', CollanaSchema);

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

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

module.exports.findAllIdApp = async function (idapp) {
  const myfind = { idapp };

  return await Collana.find(myfind).sort({title: 1}).lean();
};

module.exports.getCollaneWithTitleCount = async function (idapp, updatedata) {
  try {

    const myquery = [
      { $match: { idapp } },
      {
        $lookup: {
          from: 'products',  // Nome della tua collezione productInfo
          localField: '_id',
          foreignField: 'productInfo.idCollana',
          as: 'products'
        }
      },
      {
        $addFields: {
          myproducts: {
            $filter: {
              input: "$products",
              as: "prod",
              cond: {
                $in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
              }
            }
          }
        }
      }, {
        $project: {
          _id: 1,
          title: 1,
          idCollana: 1,
          dataOra: 1,
          quanti: { $size: '$myproducts' },
          products: {
            $map: {
              input: "$myproducts",
              as: "prod",
              in: {
                name: "$$prod.name"
              }
            }
          }
        }
      },
      { $match: { quanti: { $gt: 0 } } }, // esclude i record con quanti = 0
      { $sort: { title: 1 } } // Ordina i risultati per nome
    ];

    const result = await Collana.aggregate(myquery);

    if (updatedata) {
      for (const record of result) {
        await Collana.updateOne(
          { _id: record._id },
          { $set: { quanti: record.quanti } }
        );
      }
    }

    return result;
  } catch (error) {
    console.error('Error retrieving idCollana with title count:', error);
    throw error;
  }
}



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

