const Transaction = require('../../models/Transaction')
const Announcement = require('../../models/Announcement')

module.exports.getAllNotifs = async socket => {
  try {
    const agentInbox = await Transaction.find({ agent_id: socket.agentId, seen: false })

    socket.emit(`agent:allNotifs`, {
      agentInbox: agentInbox.length
    })
  } catch (e) {
    console.log(e)
  }
}

module.exports.notifyAgent = async (type, agent_id) => {
  try {
    const io = global._io
    const agent = io.of('/agent')
    const data = { type }

    if (type === 'updateAgentInbox') {
      const agentInbox = await Transaction.find({ agent_id, seen: false })
      data.agentInbox = agentInbox.length
    }

    agent.to(agent_id.toString()).emit(`agent:notify`, data)
  } catch (e) {
    console.log(e)
  }
}

module.exports.notifyAllAgents = type => {
  try {
    const io = global._io
    const agent = io.of('/agent')
    const data = { type }

    agent.emit('agent:notifyAll', data)
  } catch (e) {
    console.log(e)
  }
}

module.exports.fetchAnnouncements = async socket => {
  try {
    const announcements = await Announcement.find({ expired: false, isForAgents: true })
    const modifiedAnnouncements = []
    let newAnnouncementsCount = 0
    for await (const announcement of announcements) {
      const notif = { ...announcement._doc, seen: true }
      if (!notif.seenBy.includes(socket.userId)) {
        notif.seen = false
        newAnnouncementsCount++
      }
      delete notif.seenBy
      delete notif.expired
      delete notif.isForAgents
      delete notif._creator
      modifiedAnnouncements.push(notif)
    }

    socket.emit('agent:announcements', {
      newAgentAnnosCount: newAnnouncementsCount,
      agentAnnouncements: modifiedAnnouncements.reverse()
    })
  } catch (e) {
    console.log(e)
  }
}

module.exports.updateAnnouncement = async (socket, id) => {
  try {
    if (id) {
      const announcment = await Announcement.findById(id)
      if (!announcment) throw new Error('invalid announcemnet id')
      if (!announcment.seenBy.includes(socket.userId)) announcment.seenBy.push(socket.userId)
      await announcment.save()
      socket.emit('agent:fetchNewAnnouncements')
    }
  } catch (e) {
    console.log(e)
  }
}
