import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';

export type SearchSessionContextValue = {
  searchSessionId: string;
  refreshSearchSessionId: () => void;
};

export const SearchSessionContext = createContext<SearchSessionContextValue | null>(null);

export const SearchSessionProvider = ({ children }: { children: React.ReactNode }) => {
  const [searchSessionId, setSearchSessionId] = useState(() => crypto.randomUUID());

  const refreshSearchSessionId = useCallback(() => {
    setSearchSessionId(crypto.randomUUID());
  }, []);

  const value = useMemo(
    () => ({ searchSessionId, refreshSearchSessionId }),
    [searchSessionId, refreshSearchSessionId],
  );

  return <SearchSessionContext.Provider value={value}>{children}</SearchSessionContext.Provider>;
};

export function useSearchSession(): SearchSessionContextValue {
  const contextValue = useContext(SearchSessionContext);
  if (!contextValue) {
    throw new Error('useSearchSession must be used within a SearchSessionProvider');
  }
  return contextValue;
}
