import { ENV } from "../../config/environment";
import { logger } from "../../utils/logger";

export type WsHandler = (data: Record<string, unknown>) => void;

export class ConversationSocket {
  private ws: WebSocket | null = null;

  connect(conversationId: string, onMessage: WsHandler): void {
    const url = `${ENV.WS_BASE_URL}/ws/v1/conversations/${conversationId}`;
    logger.info("WS connect", url);
    this.ws = new WebSocket(url);
    this.ws.onmessage = (event) => {
      try {
        onMessage(JSON.parse(String(event.data)));
      } catch (e) {
        logger.error("WS parse error", e);
      }
    };
    this.ws.onerror = (e) => logger.error("WS error", e);
  }

  sendAudio(bytes: ArrayBuffer): void {
    this.ws?.send(bytes);
  }

  sendJson(payload: Record<string, unknown>): void {
    this.ws?.send(JSON.stringify(payload));
  }

  disconnect(): void {
    this.ws?.close();
    this.ws = null;
  }
}
