// src/providers/AppProviders.tsx
import React, { ReactNode } from 'react';
import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { queryClient } from '../config/queryClient';
import { AuthProvider } from './AuthProvider';
import { FlyersProvider } from './FlyersProvider';
import { MasterItemsProvider } from './MasterItemsProvider';
import { ModalProvider } from './ModalProvider';
import { UserDataProvider } from './UserDataProvider';
import { ErrorBoundary } from '../components/ErrorBoundary';

interface AppProvidersProps {
  children: ReactNode;
}

/**
 * A single component to group all application-wide context providers.
 * This cleans up index.tsx and makes the provider hierarchy clear.
 *
 * Provider hierarchy (from outermost to innermost):
 * 0. ErrorBoundary - Catches React errors and reports to Sentry (ADR-015)
 * 1. QueryClientProvider - TanStack Query for server state management (ADR-0005)
 * 2. ModalProvider - Modal state management
 * 3. AuthProvider - Authentication state
 * 4. FlyersProvider - Flyer data fetching
 * 5. MasterItemsProvider - Master grocery items
 * 6. UserDataProvider - User-specific data (watched items, shopping lists)
 */
export const AppProviders: React.FC<AppProvidersProps> = ({ children }) => {
  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <ModalProvider>
          <AuthProvider>
            <FlyersProvider>
              <MasterItemsProvider>
                <UserDataProvider>{children}</UserDataProvider>
              </MasterItemsProvider>
            </FlyersProvider>
          </AuthProvider>
        </ModalProvider>
        {/* React Query Devtools - only visible in development */}
        {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
      </QueryClientProvider>
    </ErrorBoundary>
  );
};
