"use client";

import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { io, Socket } from "socket.io-client";

let socket: Socket | null = null;

function getSocket() {
  if (!socket) {
    socket = io(process.env.NEXT_PUBLIC_API_URL!.replace("/api/v1", ""), {
      transports: ["websocket"],
      autoConnect: false,
    });
  }
  return socket;
}

export function useTaskSocket(orgId: string | undefined, queryKeys: string[]) {
  const qc = useQueryClient();

  useEffect(() => {
    if (!orgId) return;

    const s = getSocket();
    if (!s.connected) s.connect();

    s.emit("join:org", orgId);

    function onUpdate() {
      queryKeys.forEach((key) => qc.invalidateQueries({ queryKey: [key] }));
    }

    s.on("task:statusUpdated", onUpdate);
    s.on("payment:updated", onUpdate);
    s.on("invoice:updated", onUpdate);
    return () => {
      s.off("task:statusUpdated", onUpdate);
      s.off("payment:updated", onUpdate);
      s.off("invoice:updated", onUpdate);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orgId]);
}
