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

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

    if (!token) {
        throw new Error("No token found");
    }

    const res = await fetch("/api/auth/session", {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
        },
    });
    // console.log(res);
    if (!res.ok) {
        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");
    }

    return res.json();
};

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,
    };
};
