import { useQuery } from "@tanstack/react-query";
import { githubGetToken, githubGetAccount } from "../lib/commands";
import { fetchRemoteSpaces, type SpacesJson } from "../lib/spacesSync";

/**
 * 启动时拉取远端 spaces.json，缓存跨空间感知数据
 * 每 5 分钟自动刷新一次，未登录时不执行
 */
export function useSpacesSync(isLoggedIn: boolean) {
  return useQuery<SpacesJson | null>({
    queryKey: ["spacesSync"],
    queryFn: async () => {
      const token = await githubGetToken();
      if (!token) return null;
      const account = await githubGetAccount();
      if (!account) return null;
      return fetchRemoteSpaces(token, account.username);
    },
    enabled: isLoggedIn,
    staleTime: 5 * 60 * 1000,
    refetchInterval: isLoggedIn ? 5 * 60 * 1000 : false,
    retry: false,
  });
}
