'use client';

import { useEffect } from 'react';
import { useQueryClient, type QueryKey } from '@tanstack/react-query';

import { useSocket } from '@/providers/socket-provider';

/**
 * Subscribes to socket events and invalidates React Query caches.
 *
 * @param eventMap - Maps socket event names to arrays of query keys to invalidate.
 *
 * @example
 * useRealtimeInvalidation({
 *   'client:created': [['clients']],
 *   'client:updated': [['clients'], ['clients', clientId]],
 *   'client:archived': [['clients']],
 * });
 */
export function useRealtimeInvalidation(
  eventMap: Record<string, QueryKey[]>,
) {
  const socket = useSocket();
  const queryClient = useQueryClient();

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

    const handlers: Array<{ event: string; handler: (...args: unknown[]) => void }> = [];

    for (const [event, queryKeys] of Object.entries(eventMap)) {
      const handler = () => {
        for (const key of queryKeys) {
          queryClient.invalidateQueries({ queryKey: key });
        }
      };
      socket.on(event, handler);
      handlers.push({ event, handler });
    }

    return () => {
      for (const { event, handler } of handlers) {
        socket.off(event, handler);
      }
    };
  }, [socket, queryClient, eventMap]);
}
