// src/providers/UserDataProvider.tsx
import React, { useMemo, ReactNode } from 'react';
import { UserDataContext } from '../contexts/UserDataContext';
import { useAuth } from '../hooks/useAuth';
import { useWatchedItemsQuery } from '../hooks/queries/useWatchedItemsQuery';
import { useShoppingListsQuery } from '../hooks/queries/useShoppingListsQuery';

/**
 * Provider for user-specific data using TanStack Query (ADR-0005).
 *
 * This provider uses TanStack Query for automatic caching, refetching, and state management.
 * Data is automatically cleared when the user logs out (query is disabled),
 * and refetched when a new user logs in.
 *
 * Phase 4 Update: Removed deprecated setWatchedItems and setShoppingLists setters.
 * Use mutation hooks directly from src/hooks/mutations instead.
 */
export const UserDataProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { userProfile } = useAuth();
  const isEnabled = !!userProfile;

  const {
    data: watchedItems = [],
    isLoading: isLoadingWatched,
    error: watchedError,
  } = useWatchedItemsQuery(isEnabled);

  const {
    data: shoppingLists = [],
    isLoading: isLoadingLists,
    error: listsError,
  } = useShoppingListsQuery(isEnabled);

  const value = useMemo(
    () => ({
      watchedItems,
      shoppingLists,
      isLoading: isEnabled && (isLoadingWatched || isLoadingLists),
      error: watchedError?.message || listsError?.message || null,
    }),
    [watchedItems, shoppingLists, isEnabled, isLoadingWatched, isLoadingLists, watchedError, listsError]
  );

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