const Help = require('../models/Help')
const { _sr } = require('../plugins/serverResponses')
const { res500 } = require('../plugins/controllersHelperFunctions')
const _faSr = _sr.fa

module.exports.set = [
  async (req, res) => {
    const { helpId } = req.body
    try {
      const help = await Help.findOne()
      if (help) {
        help.helpId = helpId
        help._creator = req.user_id
        await help.save()
        return res.json({ message: _faSr.response.success_save })
      } else {
        const help = new Help({
          helpId,
          _creator: req.user_id
        })
        help.save()
        return res.json({ message: _faSr.response.success_save })
      }
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.get = [
  (req, res) => {
    const front = req.query?.front
    if (front) {
      Help.findOne({})
        .populate('helpId', '_id title')
        .exec((err, data) => {
          if (err) return res500(res, err)
          else return res.json(data)
        })
    } else {
      Help.findOne({})
        .populate('_creator', 'first_name last_name')
        .exec((err, data) => {
          if (err) return res500(res, err)
          else return res.json(data)
        })
    }
  }
]
