import { useLayoutEffect } from "react";
import type { PropsWithChildren } from "react";
import { shouldAttemptAuthRefresh } from "@modules/auth/store/authSessionHint";
import { useAuthStore } from "@modules/auth/store/authStore";
import { bootstrapSessionRefresh } from "@shared/api/client";

export function AuthBootstrap({ children }: PropsWithChildren): JSX.Element {
  const setBootstrapped = useAuthStore((state) => state.setBootstrapped);

  useLayoutEffect(() => {
    let cancelled = false;

    if (!shouldAttemptAuthRefresh()) {
      setBootstrapped(true);
      return () => {
        cancelled = true;
      };
    }

    void bootstrapSessionRefresh().finally(() => {
      if (!cancelled) {
        setBootstrapped(true);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [setBootstrapped]);

  return <>{children}</>;
}
