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 PublisherSchema = new Schema({
  idapp: {
    type: String,
  },
  name: {
    type: String,
  },
  link: {
    type: String,
  },
  img: {
    type: String,
  },
  quanti: {
    type: Number,
  },
});

var Publisher = module.exports = mongoose.model('Publisher', PublisherSchema);

module.exports.getFieldsForSearch = function () {
  return [
    { field: 'name', 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 Publisher.find(myfind).sort({ name: 1 }).lean();
};

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

    const myquery = [
      { $match: { idapp } },
      {
        $lookup: {
          from: 'products',  // Nome della tua collezione productInfo
          localField: '_id',
          foreignField: 'productInfo.idPublisher',
          as: 'products'
        }
      },
      {
        $addFields: {
          myproducts: {
            $filter: {
              input: "$products",
              as: "prod",
              cond: {
                $in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
              }
            }
          }
        }
      }, {
        $project: {
          _id: 1,
          name: 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: { name: 1 } } // Ordina i risultati per nome
    ];

    const result = await Publisher.aggregate(myquery);

    if (updatedata) {
      for (const record of result) {
        await Publisher.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; });

