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 {QueryClient, QueryClientProvider} from "react-query"
import ConfigProvider from "./ConfigProvider";

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: 2,
            refetchOnWindowFocus: false,
            staleTimeout: 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 />
                </EnhancedAuthProvider>
            </AuthProvider>
        </QueryClientProvider>
    </ConfigProvider>
);
