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

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;

        if (hasSession(sessionId)) return;
        markSession(sessionId);

        reconnectUrl =
          payload.session.reconnect_url || reconnectUrl;

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

        await createSubscription(sessionId);
        break;
      }

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

      case "session_reconnect":
        ws.close();
        connect(payload.session.reconnect_url);
        break;
    }
  });

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

module.exports = { connect };