const ContactPageMessage = require('../models/ContactPageMessage')
const {body, validationResult} = require('express-validator')
const dateformat = require('dateformat')
const v_m = require('../validation_messages')

module.exports.create = [
  [
    body('first_name')
       .notEmpty()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].required.first_name
       })
       .bail()
       .isLength({min: 2})
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].min_char.min2
       }),

    body('last_name')
       .notEmpty()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].required.last_name
       })
       .bail()
       .isLength({min: 2})
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].min_char.min2
       }),

    body('phone_number')
       .notEmpty()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].required.phone_number
       })
       .bail()
       .isNumeric()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].format.phone_number
       }),

    body('email')
       .notEmpty()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].required.email
       })
       .bail()
       .isEmail()
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].format.email
       }),

    body('reason')
       .custom((value, {req}) => {
         if (!value) return Promise.reject(v_m[req.body.locale].required.reason)
         else return true
       }),

    body('message')
       .isLength({min: 50})
       .withMessage((value, {req}) => {
         return v_m[req.body.locale].min_char.min50
       })

  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const data = {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      phone_number: req.body.phone_number,
      email: req.body.email,
      message: req.body.message,
      reason: req.body.reason,
      created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }
    const message = new ContactPageMessage(data)
    message.save((err, message) => {
      if (err) console.log(err)
      return res.json({message: v_m[req.body.locale].response.success_save})
    })
  }
]


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


module.exports.getOne = [
  (req, res) => {
    ContactPageMessage.findById(req.params.id)
       .then(message => {
         message.read = true
         message.save()
         return res.json(message)
       })
       .catch(err => {
         return res.status(404).json({message: err})
       })
  }
]
