import { useQuery } from "@tanstack/react-query";
import { useSession } from "@xtablo/shared/contexts/SessionContext";

const CHAT_API_BASE = import.meta.env.VITE_CHAT_API_URL as string;

interface UnreadCount {
  channel_id: string;
  unread_count: number;
}

export function useChatUnread() {
  const { session } = useSession();
  const token = session?.access_token;

  const { data } = useQuery({
    queryKey: ["chat-unread"],
    queryFn: async (): Promise<UnreadCount[]> => {
      const res = await fetch(`${CHAT_API_BASE}/chat/unread`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) return [];
      const json = (await res.json()) as { unread: UnreadCount[] };
      return json.unread;
    },
    enabled: !!token,
    refetchInterval: 30_000,
    refetchOnWindowFocus: true,
  });

  return {
    unreadCounts: data ?? [],
    getUnreadCount: (channelId: string) =>
      data?.find((u) => u.channel_id === channelId)?.unread_count ?? 0,
    hasUnread: (channelId: string) =>
      (data?.find((u) => u.channel_id === channelId)?.unread_count ?? 0) > 0,
  };
}
