"use client";

import { useEffect } from "react";
import { initSocket } from "@/lib/socketClient";
import { useSession } from "next-auth/react";

type CallSocketHandlers = {
  onCallStart?: (payload: unknown) => void;
  onCallEnd?: (payload: unknown) => void;
};

export function useCallSocket(handlers?: CallSocketHandlers): void {
  const { data: session } = useSession();
  const { onCallStart, onCallEnd } = handlers ?? {};

  useEffect(() => {
    const userId = (session as any)?.userId as string | undefined;
    const token = (session as any)?.accessToken as string | undefined;
    if (!userId || !token) return;

    const socket = initSocket(userId, token);
    if (!socket) return;

    const handleCallStart = (payload: unknown) => {
      if (onCallStart) {
        onCallStart(payload);
      } else {
        // Default: log for now; can be wired to UI later
        // eslint-disable-next-line no-console
        console.log("[socket] call:start", payload);
      }
    };

    const handleCallEnd = (payload: unknown) => {
      if (onCallEnd) {
        onCallEnd(payload);
      } else {
        // Default: log for now; can be wired to UI later
        // eslint-disable-next-line no-console
        console.log("[socket] call:end", payload);
      }
    };

    socket.on("call:start", handleCallStart);
    socket.on("call:end", handleCallEnd);

    return () => {
      socket.off("call:start", handleCallStart);
      socket.off("call:end", handleCallEnd);
    };
  }, [session, onCallStart, onCallEnd]);
}
