import type { ReactNode } from 'react';
import {
  QueryClient,
  QueryClientProvider,
  QueryCache,
  MutationCache,
} from '@tanstack/react-query';
import { BrowserRouter } from 'react-router-dom';
import { toast } from 'sonner';
import { Toaster } from '@/components/ui/toaster';
import { Toaster as Sonner } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider } from '@/components/theme-provider';
import { AuthProvider } from '@/contexts/AuthContext';
import { APP_DEFAULT_THEME } from '@/shared/constants/theme';
import {
  FORBIDDEN_ERROR_MESSAGE,
  isForbiddenError,
} from '@/shared/errors/errorMessages';

// Single handler so a backend 403 (permission denied) degrades to a toast
// rather than a crash or silent failure, wherever it occurs.
function notifyOnForbidden(error: unknown): void {
  if (isForbiddenError(error)) {
    toast.error(FORBIDDEN_ERROR_MESSAGE);
  }
}

const queryClient = new QueryClient({
  queryCache: new QueryCache({ onError: notifyOnForbidden }),
  mutationCache: new MutationCache({ onError: notifyOnForbidden }),
});

interface AppProvidersProps {
  readonly children: ReactNode;
}

export function AppProviders({ children }: AppProvidersProps) {
  return (
    <ThemeProvider defaultTheme={APP_DEFAULT_THEME}>
      <QueryClientProvider client={queryClient}>
        <TooltipProvider>
          <Toaster />
          <Sonner />
          <BrowserRouter>
            <AuthProvider>{children}</AuthProvider>
          </BrowserRouter>
        </TooltipProvider>
      </QueryClientProvider>
    </ThemeProvider>
  );
}
