import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import AuthProvider, {AuthContext} from "./AuthProvider";
import "bulma/css/bulma.min.css";
import "./globals.css";
import {QueryClient, QueryClientProvider} from "@tanstack/react-query"
import ConfigProvider from "./ConfigProvider";
import ControlledReactQueryDevtools from "./components/Debug/ControlledReactQueryDevtools";

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: 2,
            refetchOnWindowFocus: false,
            staleTime: 5 * 60 * 1000,
            onError: (error) => {
                if (error.message === "Unauthorized"){
                    const {logout} = queryClient
                        .getQueryCache()
                        .getAll()
                        .find(query => query.queryKey.includes("auth"))?.state?.context || {};
                    if (logout) {
                        logout();
                    }
                }
            }
        },
        mutations: {
            retry: 1,
        }
    }
});


const EnhancedAuthProvider = ({children}) => {
    const auth = React.useContext(AuthContext);
    const logout = () => {
        auth.logout();
    };

    React.useEffect(() => {
        queryClient.setQueryDefaults(["auths"], {
            context: {logout}
        });
    }, [logout]);
    return children;
}

const root =  ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <ConfigProvider>
        <QueryClientProvider client={queryClient}>
            <AuthProvider>
                <EnhancedAuthProvider>
                    <App />
                    <ControlledReactQueryDevtools />
                </EnhancedAuthProvider>
            </AuthProvider>
        </QueryClientProvider>
    </ConfigProvider>
);
