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

module.exports.broadcast = [
  [
    body('message').notEmpty().withMessage(_faSr.required.message),

    body('recievers').notEmpty().withMessage('لیست دریافت کنندگان را پر کنید')
  ],
  checkValidations(validationResult),
  async (req, res) => {
    try {
      const { message, recievers } = req.body
      const { user_id } = req
      const data = { message, recievers, _creator: user_id }
      const smsBroadcast = new SMSBroadcast(data)
      await smsBroadcast.save()
      for await (const item of recievers) {
        await SMS([item.mobile_number], message)
      }
      return res.json({ message: 'پیامک برای همه مخاطبین ارسال گردید' })
    } catch (e) {
      return res500(res, e)
    }
  }
]

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

module.exports.getOneForAdmin = [
  async (req, res) => {
    try {
      const sms = await SMSBroadcast.findById(req.params.id)
        .populate('recievers.user_id', 'mobile_number first_name last_name verity_businessCode panatech_businessCode')
        .populate('_creator', 'username first_name last_name')
      return res.json(sms)
    } catch (e) {
      return res500(res, e)
    }
  }
]
