'use client';

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

import { trackEntityView } from '@/hooks/use-search';

/**
 * Records that the user opened the given entity detail page so the
 * global search dropdown can surface it under "Recently viewed". Skips
 * the call when `id` is falsy (e.g. during a transitional render before
 * the data has loaded).
 *
 * After the track POST resolves, invalidates the recently-viewed query
 * so the search dropdown re-fetches the freshly-updated list. Without
 * this, the overlay's query cache (mounted once at the layout root)
 * stays frozen on whatever it had at first paint - typically empty -
 * and the user never sees the entity they just opened.
 */
export function useTrackEntityView(
  type:
    | 'client'
    | 'residential-client'
    | 'yacht'
    | 'company'
    | 'interest'
    | 'residential-interest'
    | 'berth'
    | 'invoice'
    | 'expense'
    | 'document',
  id: string | null | undefined,
): void {
  const queryClient = useQueryClient();

  useEffect(() => {
    if (!id) return;
    void trackEntityView(type, id).then(() => {
      queryClient.invalidateQueries({ queryKey: ['search', 'recently-viewed'] });
    });
  }, [type, id, queryClient]);
}
