const WebSocket = require("ws");
const { createSubscription } = require("./subscriptions");
const { handleEvent } = require("./handler");

let reconnectUrl = "wss://eventsub.wss.twitch.tv/ws";

function connect(url = reconnectUrl) {
  const ws = new WebSocket(url);

  ws.on("open", () => {
    console.log("🔌 Connected to Twitch EventSub");
  });

  ws.on("message", async (raw) => {
    const msg = JSON.parse(raw);
    const { metadata, payload } = msg;

    switch (metadata.message_type) {
      case "session_welcome": {
        const sessionId = payload.session.id;

        console.log("🟢 Session:", sessionId);

        reconnectUrl =
          payload.session.reconnect_url ||
          "wss://eventsub.wss.twitch.tv/ws";

        await createSubscription(sessionId);
        break;
      }

      case "notification":
        handleEvent(payload);
        break;

      case "session_reconnect":
        console.log("♻️ Reconnecting...");
        ws.close();
        connect(payload?.session?.reconnect_url || reconnectUrl);
        break;

      case "session_keepalive":
        break;
    }
  });

  ws.on("close", () => {
    console.log("❌ Disconnected. Reconnecting...");
    setTimeout(() => connect(), 3000);
  });

  ws.on("error", (err) => {
    console.error("WebSocket error:", err.message);
  });
}

module.exports = { connect };