import { env } from "@haushaltsApp/env/native";

const WS_BASE_URL = env.EXPO_PUBLIC_SERVER_URL.replace(/^http/, "ws");

export type WSEventHandler<T> = (data: T) => void;

export class WebSocketClient<T = unknown> {
  private ws: WebSocket | null = null;
  private handlers: Map<string, WSEventHandler<T>[]> = new Map();

  connect(path: string): void {
    this.ws = new WebSocket(`${WS_BASE_URL}${path}`);

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data as string) as { type: string } & T;
        const typeHandlers = this.handlers.get(data.type) ?? [];
        for (const handler of typeHandlers) {
          handler(data);
        }
      } catch {
        console.error("Failed to parse WebSocket message");
      }
    };

    this.ws.onerror = (error) => {
      console.error("WebSocket error:", error);
    };
  }

  on(event: string, handler: WSEventHandler<T>): void {
    const existing = this.handlers.get(event) ?? [];
    this.handlers.set(event, [...existing, handler]);
  }

  send(data: unknown): void {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
    }
  }

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