const moment = require('moment-jalaali')
const { body, validationResult } = require('express-validator')
const BufferRequest = require('../models/BufferRequest')
const { _sr } = require('../plugins/serverResponses')
const {
  res404,
  res406,
  res500,
  checkValidations,
  generateRandomDigits
} = require('../plugins/controllersHelperFunctions')
const { SMS } = require('../plugins/SMS_Module')
// const { phrases } = require('../plugins/SMS_Phrases')
// const { notifyAgent } = require('../WebSocket/controllers/agent_EventsController')
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
const _faSr = _sr.fa

// date formaters
function ArpaDateFormat(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

function SmsDateFormat(date) {
  return moment(date).format('jYYYY/jMM/jDD')
}

/// ///////////////// agent
module.exports.add_buffer_request = [
  async (req, res) => {
    try {
      const { user_id, agent_id } = req
      const thisTime = Date.now()

      const data = {
        user_id,
        agent_id,
        createDate: ArpaDateFormat(thisTime),
        statusHistory: [{ status: 'temp', date: thisTime }]
      }

      const br = BufferRequest(data)
      await br.save()
      return res.json({ message: _faSr.response.success_save })
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.add_buffer_to_br = [
  [
    body('ItemName').notEmpty().withMessage('نام کالا را مشخص کنید'),

    body('ItemID').notEmpty().withMessage('Include ItemID'),

    body('ItemCode').notEmpty().withMessage('Include ItemCode'),

    body('bufferQuantity')
      .notEmpty()
      .withMessage('تعداد قطعه را مشخص کنید')
      .isNumeric()
      .withMessage(_faSr.format.number)
  ],
  checkValidations(validationResult),
  async (req, res) => {
    try {
      const brId = req.params?.brId
      const { ItemName, ItemID, ItemCode, bufferQuantity } = req.body

      const data = {
        ItemName,
        ItemID,
        ItemCode,
        bufferQuantity
      }

      const br = await BufferRequest.findById(brId)
      br.items.push(data)
      await br.save()
      return res.json({ message: _faSr.response.success_save })
    } catch (e) {
      return res404(res, e)
    }
  }
]

module.exports.remove_buffer_from_br = [
  async (req, res) => {
    try {
      const bufferItemId = req.params?.bufferItemId
      if (!bufferItemId) throw new Error('invalid id')
      const br = await BufferRequest.findOne({ 'items._id': bufferItemId })
      br.items.id(bufferItemId).remove()
      await br.save()
      return res.json({ message: _faSr.response.success_remove })
    } catch (e) {
      console.log(e)
      return res500(res, e)
    }
  }
]

module.exports.update_br_description = [
  (req, res) => {
    const { description } = req.body
    const data = {
      description
    }
    BufferRequest.findByIdAndUpdate(req.params?.id, data, (err, oldData) => {
      if (err) return res404(res, 'invalid id')
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.get_all_br_for_agent = [
  (req, res) => {
    const agent_id = req.agent_id
    BufferRequest.find({ agent_id }, (err, data) => {
      if (err) return res500(res, err)
      else return res.json(data)
    })
  }
]

module.exports.get_one_br_for_agent = [
  (req, res) => {
    BufferRequest.findById(req.params.id)
      .populate(
        'agent_id',
        'full_name province_name city_name address agent_code postal_code tel_number fax_number mobile_number'
      )
      .exec((err, data) => {
        if (err || !data) return res404(res, err)
        else return res.json(data)
      })
  }
]

module.exports.delete_br = [
  async (req, res) => {
    try {
      const br = await BufferRequest.findById(req.params?.id)
      if (br.status !== 'temp') return res406(res, 'نمیتوانید درخواست ارسال شده را حذف کنید')
      await br.remove()
      return res.json({ message: _faSr.response.success_remove })
    } catch (e) {
      return res404(res, 'invalid id')
    }
  }
]

module.exports.change_br_status_to_sent_by_agent = [
  async (req, res) => {
    try {
      const thisTime = Date.now()

      const br = await BufferRequest.findById(req.params?.id).populate('agent_id')
      if (!br) throw new Error('invalid br id')
      const totalBr = await BufferRequest.find({ status: { $ne: 'temp' } })

      if (br.status !== 'temp') return res406(res, 'این فرم قبلا برای آسان سرویس ارسال شده')
      if (!br.items.length) return res406(res, 'هیچ قطعه ای به فرم اضافه نکرده اید')

      // generate tracking code
      const trackingCode = 'BP' + totalBr.length.toString().padStart(4, '0') + generateRandomDigits(2)

      // modify br
      br.status = 'sent'
      br.statusHistory.push({ status: 'sent', date: thisTime })
      br.trackingCode = trackingCode
      br.sendDate = ArpaDateFormat(thisTime)

      // send sms for agent
      const smsMsg = [
        ' نماینده گرامی درخواست کالای بافر شما در تاریخ ',
        SmsDateFormat(thisTime),
        ' با کد پیگیری ',
        trackingCode,
        ' برای شرکت ارسال شد. '
      ]

      SMS([br.agent_id.mobile_number], smsMsg.join(''))

      await br.save()
      notifyAdmin('updateNewBufferRequests')
      return res.json({ message: 'درخواست کالای بافر ارسال شد' })
    } catch (e) {
      console.log(e)

      return res404(res, e)
    }
  }
]

/// ///////////////// admin
module.exports.get_all_br_for_admin = [
  async (req, res) => {
    try {
      const brList = await BufferRequest.find({
        status: { $ne: 'temp' }
      }).populate(
        'agent_id',
        'full_name agent_code mobile_number national_code province_name city_name province_id city_id'
      )
      return res.json(brList)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.get_oneAgent_br_for_admin = [
  async (req, res) => {
    const agent_id = req.params?.agent_id
    try {
      const brList = await BufferRequest.find({
        status: { $ne: 'temp' },
        agent_id
      }).populate('agent_id', 'full_name agent_code mobile_number national_code province_name city_name')
      return res.json(brList)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.get_one_br_for_admin = [
  async (req, res) => {
    try {
      const { user_id } = req
      const thisTime = Date.now()
      const br = await BufferRequest.findById(req.params?.id)
        .populate(
          'agent_id',
          'agent_code full_name mobile_number fax_number tel_number province_name city_name national_code address postal_code store_name'
        )
        .populate('_openedBy', 'username first_name last_name')
        .populate('_updatedBy', 'username first_name last_name')
      if (!br.seen) {
        br.seen = true
        br._openedBy = user_id
        br.status = 'ongoing'
        br.statusHistory.push({ status: 'ongoing', date: thisTime })
        await br.save()

        const smsMsg = [
          ' نماینده گرامی درخواست کالای بافر شما با کد پیگیری ',
          br.trackingCode,
          ' در تاریخ ',
          SmsDateFormat(thisTime),
          ' در دست اقدام قرار گرفت. '
        ]

        SMS([br.agent_id.mobile_number], smsMsg.join(''))
        notifyAdmin('updateNewBufferRequests')
      }
      return res.json(br)
    } catch (e) {
      return res500(res, e)
    }
  }
]

module.exports.change_br_status_by_admin = [
  [
    body('status')
      .notEmpty()
      .withMessage('status is required')
      .bail()
      .custom((value, { req }) => {
        const acceptablvalues = ['waiting', 'delivered']
        if (!acceptablvalues.includes(value)) return Promise.reject(new Error('invalid status'))
        else return true
      })
  ],
  checkValidations(validationResult),
  async (req, res) => {
    const { user_id } = req
    const { status, deliveryCode } = req.body
    const thisTime = Date.now()

    try {
      const br = await BufferRequest.findById(req.params?.id).populate('agent_id')
      if (!br) throw new Error('invalid br id')

      // check statuses
      const statusErrMsg = 'invalid status for this time'
      if (br.status === 'delivered') return res406(res, statusErrMsg)
      if (br.status === 'waiting' && status === 'waiting') return res406(res, statusErrMsg)

      // save status
      br._updatedBy = user_id
      br.status = status
      br.statusHistory.push({ status, date: thisTime })

      let smsMessage
      // differenet status methods
      if (status === 'waiting') {
        smsMessage = [
          ' نماینده گرامی درخواست کالای بافر شما با کد پیگیری ',
          br.trackingCode,
          ' در تاریخ ',
          SmsDateFormat(thisTime),
          ' در انتظار قطعه میباشد. '
        ]
      }

      if (status === 'delivered') {
        if (deliveryCode) br.deliveryCode = deliveryCode

        function deliveryCodePhrase() {
          if (deliveryCode.length) return `کد پیگیری مرسوله: ${deliveryCode}` + '\n'
          else return ''
        }

        smsMessage = [
          ' نماینده گرامی درخواست کالای بافر شما با کد پیگیری ',
          br.trackingCode,
          ' در تاریخ ',
          SmsDateFormat(thisTime),
          ' تحویل شد. ',
          '\n',
          deliveryCodePhrase()
        ]
      }

      await SMS([br.agent_id.mobile_number], smsMessage.join(''))
      await br.save()
      return res.json({ message: _faSr.response.success_save })
    } catch (e) {
      return res500(res, e)
    }
  }
]
