import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useEffect } from "react";
import { useSessionStore } from "../lib/store/sessionStore";

const fetchSession = async () => {
	const token = localStorage.getItem("auth_token");

	if (!token) {
		throw new Error("No token found");
	}
	try {
		const res = await axios.get("/api/auth/session", {
			headers: {
				"Content-Type": "application/json",
			},
			withCredentials: true,
		});

		if (res.status === 401) {
			localStorage.removeItem("auth_token");
			// remove these for a while if no session just until fully to 2.0 and clearly no one has ran lstv1 in a long time
			localStorage.removeItem("ally-supports-cache");
			localStorage.removeItem("auth-storage");
			localStorage.removeItem("nextauth.message");
			localStorage.removeItem("prod");

			throw new Error("Session not found");
		}

		const userRoles = await axios.get("/api/auth/getuseraccess", {
			withCredentials: true,
		});

		const userData = {
			...res.data,
			data: {
				...res.data.data,
				user: {
					...res.data.data.user,
					roles: userRoles.data.data,
				},
				token: "Just a token as this will be removed in the future",
			},
		};

		return userData;
	} catch (error) {
		localStorage.removeItem("auth_token");
		// remove these for a while if no session just until fully to 2.0 and clearly no one has ran lstv1 in a long time
		localStorage.removeItem("ally-supports-cache");
		localStorage.removeItem("auth-storage");
		localStorage.removeItem("nextauth.message");
		localStorage.removeItem("prod");

		throw new Error("Session not found");
	}
};

export const useSession = () => {
	const { setSession, clearSession, token } = useSessionStore();

	// Fetch session only if token is available
	const { data, status, error } = useQuery({
		queryKey: ["session"],
		queryFn: fetchSession,
		enabled: !!token, // Prevents query if token is null
		staleTime: 60 * 1000,
		//gcTime: 10 * 60 * 1000, // 10 mins
		refetchOnWindowFocus: true,
		refetchInterval: 1000 * 60 * 2, // Auto-refetch every 2 minutes
	});
	useEffect(() => {
		if (data) {
			setSession(data.data.user, data.data.token);
		}
		if (error) {
			clearSession();
		}
	}, [data, error]);

	return {
		session: data && token ? { user: data.user, token: data.token } : null,
		status,
		error,
	};
};
