"use client";

import { useEffect } from "react";

import { createChatWebSocket } from "@/core/net/chat-websocket";
import type { LoginStatus } from "@/data/schemas/auth";
import { getSessionAccessToken } from "@/lib/auth/auth_session";
import { useChatDispatch } from "@/stores/chat/chat-context";

export function useChatCommercialMessages(input: {
  characterId: string;
  loginStatus: LoginStatus;
}) {
  const chatDispatch = useChatDispatch();

  useEffect(() => {
    if (input.loginStatus === "notLoggedIn" || input.loginStatus === "guest") {
      return;
    }

    let disposed = false;
    let socket: ReturnType<typeof createChatWebSocket> | null = null;
    void getSessionAccessToken().then((token) => {
      if (disposed || !token) return;
      socket = createChatWebSocket(token);
      socket.onCommercialMessage = (message) => {
        if (message.characterId !== input.characterId) return;
        chatDispatch({ type: "ChatCommercialMessageReceived", message });
      };
      socket.connect();
    });

    return () => {
      disposed = true;
      socket?.disconnect();
    };
  }, [chatDispatch, input.characterId, input.loginStatus]);
}
