const mongoose = require("mongoose");

const FeedbackEntries = mongoose.model("feedbackEntries");


/* * Gets called from the index.router.js
        * Records data in DB */
module.exports.saveEntries = (req, res, next) => {
    FeedbackEntries.create({article_id: req.body.article_id, title: req.body.title, rating : req.body.rating , 
      user :req.body.user, 
      search_query: req.body.search_query }, function(err, myobj) {
        if (err) { 
          return handleError(err); 
        } else { 
          res.sendStatus(200); 
        }
      });
}

/* * Gets called from the index.router.js
        * Returns the number of interactions per query */
module.exports.feedbackInteractions = (req, res, next) => {
  FeedbackEntries.aggregate([
    {
      '$group': {
        '_id': '$search_query', 
        'count': {
          '$sum': 1
        }
      }
    },
    {
      '$project': {
        '_id': 0, 
        'queryName': '$_id', 
        'feedbackInteractions': '$count'
      }
    },
    {
      '$sort' : { 'feedbackInteractions' : -1 }
    }
  ]).exec((err, populatedResult) => {
    if(err) {
      res.sendStatus(404); 
    } else {
        //use this log to debug the JSON ouput
        // console.log(JSON.stringify(populatedResult));
        //res.status(200).send(populatedResult);
        return res.status(200).json({
            status: true,
            interactions: populatedResult
        });
    };
  });
};