const { getIO } = require("./socketIO")

/**
 * Sends a ticket creation event to the hitphone socket client
 * 
 * @param {Object} ticketInformations Object representing the information needed to notify the Hitphone front-end
 * @param {string} ticketInformations.companyId Company codWeb or identifier (Example: 1)
 * @param {string} ticketInformations.extension Agent Extension that received the call (Example: 3005)
 * @param {string} ticketInformations.ticketUrl URL of ticket created
 */
function sendEventTicketCreatedToSocket (ticketInformations) {
  const { companyId, extension, ticketUrl } = ticketInformations
  try {
    console.log(`${new Date().toISOString()} ==========> sendEventTicketCreatedToSocket: Sending ticket event created to socket with data ${JSON.stringify(ticketInformations)}`)
  
    const io = getIO()
    const extensionAgentRoom = `${companyId}@${extension}`
    const roomExists = io.sockets.adapter.rooms.has(extensionAgentRoom)
    if (roomExists) { 
      io.to(extensionAgentRoom).emit('ticket-created', { url: ticketUrl } ) 
      console.log(`${new Date().toISOString()} ==========> sendEventTicketCreatedToSocket: Ticket-created event successfully sent to: ${JSON.stringify(ticketInformations)}`)
    } else {
      console.log(`${new Date().toISOString()} ==========> sendEventTicketCreatedToSocket: Unable to send the event ticket-created because the Extension Agent (CompanyID: ${companyId} | Extension: ${extension}) is not connected to the Hitphone`)
    }
  } catch (error) {
    console.log(`${new Date().toISOString()} ==========> sendEventTicketCreatedToSocket: Unable to send the event ticket-created to Extension Agent (CompanyID: ${companyId} | Extension: ${extension}) because an error occurred: \n${error}`)
  }
}

module.exports = sendEventTicketCreatedToSocket
