const axios = require("axios");
const _ = require("lodash");
const { default: InstanceMgr } = require("../utils/instanceMgr"); // For deep object comparison

// Constants
const ALERTS_REDIS_KEY = "alerts_data"; // The key under which we'll store alerts in Redis
const GLOBAL_SOCKET_ID = "global"; // Use 'global' as a socketId to store global data

const ALERT_FILE_URL = InstanceMgr({
  imex: "https://images.imex.online/alerts/alerts-imex.json",
  rome: "https://images.imex.online/alerts/alerts-rome.json"
});

const alertCheck = async (req, res) => {
  // Access Redis helper functions
  const { ioRedis, logger } = req;
  const { getSessionData, setSessionData } = req.sessionUtils;

  try {
    // Get the JSON Alert file from the server
    const response = await axios.get(ALERT_FILE_URL);
    const currentAlerts = response.data;
    // Retrieve stored alerts from Redis using a global socketId
    const storedAlerts = await getSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY);
    if (!storedAlerts) {
      // Alerts not in Redis, store them
      await setSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY, currentAlerts);
      logger.logger.debug("Alerts added to Redis for the first time.");

      // Emit to clients
      if (ioRedis) {
        ioRedis.emit("bodyshop-message", {
          type: "alert-update",
          payload: currentAlerts
        });
        logger.logger.debug("Alerts emitted to clients for the first time.");
      } else {
        logger.log("Socket.IO instance not found. (1)", "error");
      }

      return res.status(200).send("Alerts added to Redis and emitted to clients.");
    } else {
      // Alerts are in Redis, compare them
      if (!_.isEqual(currentAlerts, storedAlerts)) {
        // Alerts are different, update Redis and emit to clients
        await setSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY, currentAlerts);
        logger.logger.debug("Alerts updated in Redis.");

        // Emit the new alerts to all connected clients
        if (ioRedis) {
          ioRedis.emit("bodyshop-message", {
            type: "alert-update",
            payload: currentAlerts
          });
          logger.logger.debug("Alerts emitted to clients after update.");
        } else {
          logger.log("Socket.IO instance not found. (2)", "error");
        }

        return res.status(200).send("Alerts updated in Redis and emitted to clients.");
      } else {
        return res.status(200).send("No changes in alerts.");
      }
    }
  } catch (error) {
    logger.log("Error in alertCheck:", "error", null, null, {
      error: {
        message: error.message,
        stack: error.stack
      }
    });
    return res.status(500).send("Internal server error.");
  }
};

module.exports = { alertCheck };
