import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect } from "react";
import { useSessionStore } from "@/lib/store/sessionStore";
import { useAuthStore } from "@/lib/store/useAuthStore";
import { useGetUserRoles } from "@/lib/store/useGetRoles";
import { useSettingStore } from "@/lib/store/useSettings";
import { useSubModuleStore } from "@/lib/store/useSubModuleStore";
import { useModuleStore } from "../../lib/store/useModuleStore";

const queryClient = new QueryClient();

const reAuth = async (username: string, password: string) => {
	const { setSession } = useSessionStore();
	try {
		const response = await fetch("/api/auth/login", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
			},
			body: JSON.stringify({
				username: username,
				password: password,
			}),
		});

		const data = await response.json();

		// Store token in localStorage
		// localStorage.setItem("auth_token", data.data.token);
		if (data.success) {
			const prod = btoa(`${username.toLowerCase()}:${password}`);
			const prodUser = { ...data.user, prod: prod };

			setSession(prodUser, data.data.token);
		}

		//console.log(data);
	} catch (err) {
		console.log(err);
	}
};
export const SessionProvider = ({
	children,
}: {
	children: React.ReactNode;
}) => {
	const { fetchModules } = useModuleStore();
	const { fetchSettings } = useSettingStore();
	const { fetchUserRoles } = useGetUserRoles();
	const { fetchSubModules } = useSubModuleStore();
	const { username, password } = useAuthStore();

	useEffect(() => {
		if (username !== "") {
			reAuth(username, password);
		}

		fetchModules();
		fetchSettings();
		fetchUserRoles();
		fetchSubModules();
	}, []);

	return (
		<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
	);
};
