import { useCurrentUser } from "@indietabletop/appkit";
import { useMemo, type ReactNode } from "react";
import { SWRConfig } from "swr";

/**
 * Links SWR cache to the current user. This makes sure that if a user logs
 * out and continues using the app in an anonymous state, they will not be
 * shown stale data.
 */
export function CacheProvider(props: { children: ReactNode }) {
  const currentUser = useCurrentUser();
  const cacheKey = currentUser ? currentUser.id : "anonymous";

  const provider = useMemo(() => {
    console.info(`Using SWR cache for "${cacheKey}"`);
    return () => new Map();
  }, [cacheKey]);

  return <SWRConfig value={{ provider }}>{props.children}</SWRConfig>;
}
