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 productInfoSchema = new Schema({
  idapp: {
    type: String,
  },
  department: {
    type: String, ref: 'Department'
  },
  code: {
    type: String,
    unique: true,
    required: true,
  },
  id_wp: {  // id in wordpress
    type: String,
  },
  codice_EAN: {
    type: String,
  },
  barcode: {
    type: String,
  },
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  short_descr: {
    type: String,
  },
  idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }],
  idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
  color: {
    type: String
  },
  size: {
    type: String  // 11x4x3
  },
  weight: {
    type: Number
  },
  weight_lordo: {
    type: Number
  },
  unit: {
    type: Number,
    default: 0,
  },
  unit_lordo: {
    type: Number,
    default: 0,
  },
  sfuso: {  // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
    type: Boolean
  },
  vegan: {
    type: Boolean
  },
  icon: {
    type: String,
  },
  img: {
    type: String,
  },
  imagefile: {
    type: String,
  },
  vers_img: {
    type: Number,
  },
  image_link: {
    type: String,
  },
  link_scheda: {
    type: String,
  },
  link: {
    type: String,
  },
  checkout_link: {
    type: String,
  },
  versioneGM: {
    type: String,
  },
  img2: {
    type: String,
  },
  img3: {
    type: String,
  },
  img4: {
    type: String,
  },
  ingredienti: {
    type: String,
  },
  valori_nutrizionali: {
    type: String,
  },
  note: {
    type: String,
  },
  idAuthors: [{ type: Schema.Types.ObjectId, ref: 'Author' }],
  idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher' },
  collezione: {
    type: String,
  },
  date_publishing: {
    type: Date,
  },
  date_publishing_ts: {
    type: Number,
  },
  productTypes: [{
    type: Number,
  }],

});

var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema);

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, code, id) {
  let myfind = {};
  let myqueryadd = {};
  let query = [];

  try {

    if (idapp)
      myfind = { idapp };

    if (code) {
      myfind = { ...myfind, code }
    }
    if (id) {
      myqueryadd = {
        $addFields: {
          myId1: {
            $toObjectId: id,
          },
        },
      }
      myfind = {
        $expr: {
          $eq: ["$_id", "$myId1"],
        },
      }

      query.push(myqueryadd);
    }

    query.push(
      { $match: myfind },
      {
        $lookup: {
          from: 'catprods',
          localField: 'idCatProds',
          foreignField: '_id',
          as: 'catprods'
        }
      },
      {
        $lookup: {
          from: 'authors',
          localField: 'idAuthors',
          foreignField: '_id',
          as: 'authors'
        }
      },
      {
        $lookup: {
          from: 'publishers',
          localField: 'idPublisher',
          foreignField: '_id',
          as: 'publisher'
        }
      },
      {
        $lookup: {
          from: 'subcatprods',
          localField: 'idSubCatProds',
          foreignField: '_id',
          as: 'subcatprods'
        }
      },
      {
        $sort: {
          name: 1 // 1 for ascending order, -1 for descending order
        }
      },
    );

    let ris = await productInfo.aggregate(query)

    return ris;

  } catch (e) {
    console.error('E', e);
  }

};

module.exports.getProductByCode = function (idapp, code) {
  return productInfo.findAllIdApp(idapp, code);
}
module.exports.replaceProductImgToImageFile = async function () {
  const ProductInfo = this;

  let abilitaserver = true;

  if (abilitaserver) {
    // const result = await ProductInfo.updateMany({ "img": { $exists: true } }, { $rename: { 'img': 'imagefile' } });

    // Trova tutti i documenti con il campo 'img' che esiste
    const documents = await ProductInfo.find({ "img": { $exists: true } });

    // Aggiorna ciascun documento
    for (let doc of documents) {
      if (doc.img && doc.img.startsWith('upload/products/')) {
        // Rimuovi il prefisso '/upload/products' dal campo `img`
        doc.imagefile = doc.img.replace(/^\upload\/products\//, '');
        doc.img = undefined; // Può anche rimuovere il campo img corrente se desiderato
        await doc.save(); // Salva il documento aggiornato
      }
    }

    console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);

  } else {
    const documents = await ProductInfo.find({ "imagefile": { $exists: true } });

    // Aggiorna ciascun documento
    for (let doc of documents) {
      if (doc.imagefile && doc.imagefile.startsWith('upload/products/')) {
        // Rimuovi il prefisso '/upload/products' dal campo `img`
        doc.imagefile = doc.imagefile.replace(/^\upload\/products\//, '');
        await doc.save(); // Salva il documento aggiornato
      }
    }

    console.log(`Updated ${documents.length} document(s) with new imagefile paths.`);


  }


  await ProductInfo.updateMany({}, { 'vers_img': 0 });

  console.log(`Updated ${result.modifiedCount} document(s).`);

};

module.exports.correggiProductTypes = async function () {
  const ProductInfo = this;
  const bulkOps = [];

  try {
    // Fase di aggregazione
    const cursor = ProductInfo.aggregate([
      {
        $project: {
          _id: 1,
          productType: 1,
          productTypes: [{ $ifNull: ['$productType', 10] }]
        }
      }
    ]).cursor({ batchSize: 1000 }).exec();

    // Itera attraverso ogni documento utilizzando il cursore
    for await (const doc of cursor) {
      bulkOps.push({
        updateOne: {
          filter: { _id: doc._id },
          update: {
            $set: { productTypes: doc.productTypes },
            $unset: { productType: "" }
          }
        }
      });

      // Scrivi i batch di operazioni ogni 1000 documenti
      if (bulkOps.length === 1000) {
        await ProductInfo.bulkWrite(bulkOps);
        bulkOps.length = 0;
      }
    }

    // Scrivi eventuali operazioni rimanenti
    if (bulkOps.length > 0) {
      await ProductInfo.bulkWrite(bulkOps);
    }

    console.log('ProductInfo.productType converted to productTypes array and saved');
  } catch (err) {
    console.error('Error converting ProductInfo.productType:', err);
  }
}

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