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

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

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

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

const CatProdSchema = new Schema({
  idapp: {
    type: String,
  },
  idArgomento: {
    type: Number,
  },
  name: {
    type: String,
    index: 1,
  },
  descr_estesa: {
    type: String,
  },
  img: {
    type: String,
  },
  icon: {
    type: String,
  },
  color: {
    type: String,
  },
  quanti: {
    type: Number,
  }
});

CatProdSchema.statics.getAllCategories = function (callback) {
  CatProd.find(callback)
}

CatProdSchema.statics.getCatProdById = function (id, callback) {
  CatProd.findById(id, callback);
}

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

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

CatProdSchema.statics.findAllIdApp = async function (idapp) {
  const myfind = { idapp };

  return await CatProd.find(myfind).sort({ name: 1 }).lean();
};

/*CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
  try {
    const toDelete = await CatProd.aggregate([
      { $match: { idapp } },
      {
        $lookup: {
          from: 'products',  
          localField: '_id',
          foreignField: 'idCatProds',
          as: 'products'
        }
      },
      {
        $project: {
          _id: 1,
          name: 1,
          quanti: { $size: '$products' } // Conta il numero di prodotti per ciascun CatProd
        }
      },
      { $match: { quanti: 0 } },
    ]);

    if (toDelete.length > 0) {
      const ids = toDelete.map(x => x._id);
      const ris = await CatProd.deleteMany({ _id: { $in: ids } });
      const deletedRecs = toDelete.map(x => ({ _id: x._id, name: x.name }));
      if (deletedRecs.length > 0) {
        return `Lista Argomenti cancellati: ${deletedRecs.map(x => x.name).join(', ')}`;
      }
    }
    return "Nessun argomento cancellato";

  } catch (error) {
    console.error('Error UpdateCatDeleteEmpty:', error);
    return error;
  }

};*/

CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updatedata) {
  try {

    const myquery = [
      { $match: { idapp } },
      {
        $lookup: {
          from: 'products',  // Nome della tua collezione productInfo
          localField: '_id',
          foreignField: 'productInfo.idCatProds',
          as: 'products'
        }
      },
      {
        $addFields: {
          myproducts: {
            $filter: {
              input: "$products",
              as: "prod",
              cond: {
                $in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
              }
            }
          }
        }
      }, {
        $project: {
          _id: 1,
          name: 1,
          idArgomento: 1,
          descr_estesa: 1,
          img: 1,
          icon: 1,
          color: 1,
          quanti: { $size: '$myproducts' }, // Conta il numero di prodotti per ciascun CatProd
          /*products: {
            $map: {
              input: "$myproducts",
              as: "prod",
              in: {
                name: "$$prod.name"
              }
            }
          }*/
        }
      },
      { $sort: { name: 1 } } // Ordina i risultati per nome
    ];

    const result = await CatProd.aggregate(myquery);

    // console.log(JSON.stringify(myquery, null, 2))

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

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


const CatProd = mongoose.model('CatProd', CatProdSchema);

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



module.exports = CatProd;
