const { body, validationResult } = require('express-validator')
const ContactPageMessage = require('../models/ContactPageMessage')
const { _sr } = require('../plugins/serverResponses')
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
const { res404 } = require('../plugins/controllersHelperFunctions')

const _faSr = _sr.fa

module.exports.create = [
  [
    body('full_name')
      .notEmpty()
      .withMessage(_faSr.required.name)
      .bail()
      .isLength({ min: 2 })
      .withMessage(_faSr.min_char.min2),

    body('email').notEmpty().withMessage(_faSr.required.email).bail().isEmail().withMessage(_faSr.format.email),

    body('message').isLength({ min: 20 }).withMessage(_faSr.min_char.min20)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() })

    const data = {
      full_name: req.body.full_name,
      email: req.body.email,
      message: req.body.message
    }
    const message = new ContactPageMessage(data)
    message.save((err, message) => {
      if (err) console.log(err)
      notifyAdmin('updateUnreadCuMsgs')
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.getAll = [
  (req, res) => {
    ContactPageMessage.find({}).sort({created_at:1})
      .select('-message')
      .then(messages => {
        return res.json(messages)
      })
      .catch(err => {
        return res.status(500).json({ message: err })
      })
  }
]

module.exports.getOne = [
  async (req, res) => {
    try {
      const message = await ContactPageMessage.findById(req.params.id).populate('read_by', 'first_name last_name')
      if (!message.read) {
        message.read_by = req.user_id
        message.read = true
        await message.save()
        notifyAdmin('updateUnreadCuMsgs')
      }
      return res.json(message)
    } catch (e) {
      return res404(res, _faSr.not_found.item_id)
    }
  }
]
