import SuperTokens from "supertokens-web-js";
import Session from "supertokens-web-js/recipe/session";
import Passwordless from "supertokens-web-js/recipe/passwordless";
import { appInfo } from "./config";
import { logger } from "./";

let refreshPromise: Promise<boolean> | null = null;

export const resetRefreshFlag = () => {
  refreshPromise = null;
};

export const getOrCreateRefreshPromise = (refreshFn: () => Promise<boolean>): Promise<boolean> => {
  if (refreshPromise) {
    logger.info("Reusing existing refresh promise");
    return refreshPromise;
  }

  logger.info("Creating new refresh promise");
  refreshPromise = refreshFn()
    .then((result) => {
      logger.info("Refresh completed successfully:", result);
      setTimeout(() => {
        refreshPromise = null;
      }, 500);
      return result;
    })
    .catch((error) => {
      logger.error("Refresh failed:", error);
      refreshPromise = null;
      throw error;
    });

  return refreshPromise;
};

export const frontendConfig = () => {
  return {
    appInfo,
    recipeList: [
      Passwordless.init(),
      Session.init({
        tokenTransferMethod: "cookie",
        sessionTokenBackendDomain: undefined,
        preAPIHook: async (context) => {
          context.requestInit.credentials = "include";
          return context;
        },
      }),
    ],
  };
};

let initialized = false;

export function ensureSuperTokensFrontend() {
  if (typeof window === "undefined") return;

  if (!initialized) {
    SuperTokens.init(frontendConfig());
    initialized = true;
    logger.info("SuperTokens initialized");
  }
}
