const { body, validationResult } = require('express-validator')
const FAQ = require('../models/FAQ')
const { _sr } = require('../plugins/serverResponses')
const { res404, res500, checkValidations } = require('../plugins/controllersHelperFunctions')
const _faSr = _sr.fa

module.exports.create = [
  [
    body('question').notEmpty().withMessage(_faSr.required.question),

    body('answer').notEmpty().withMessage(_faSr.required.answer)
  ],
  checkValidations(validationResult),
  (req, res) => {
    const data = {
      _creator: req.user_id,
      question: req.body.question,
      answer: req.body.answer
    }

    const faq = new FAQ(data)
    faq.save(cb => {
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.getAll = [
  (req, res) => {
    FAQ.find({}, (err, data) => {
      if (err) return res500(res, err)
      return res.json(data)
    })
  }
]

module.exports.getOne = [
  (req, res) => {
    FAQ.findById(req.params.id)
      .populate('_creator', 'first_name last_name')
      .exec((err, data) => {
        if (err) return res.status(404).json({ message: err })
        return res.json(data)
      })
  }
]

module.exports.update = [
  [
    body('question').notEmpty().withMessage(_faSr.required.question),

    body('answer').notEmpty().withMessage(_faSr.required.answer)
  ],
  checkValidations(validationResult),
  (req, res) => {
    const data = {
      _creator: req.user_id,
      question: req.body.question,
      answer: req.body.answer
    }

    FAQ.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) return res404(res, err)
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.delete = [
  (req, res) => {
    FAQ.findByIdAndDelete(req.params.id, (err, oldData) => {
      if (err) return res.status(404).json({ message: err })
      return res.json({ message: _faSr.response.success_remove })
    })
  }
]
