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 refreshAttemptCount = 0;

export const resetRefreshFlag = () => {
  refreshAttemptCount = 0;
};

const setupFetchInterceptor = () => {
  if (typeof window === 'undefined') return;

  const originalFetch = window.fetch;
  //@ts-ignore
  window.fetch = async (resource: RequestInfo | URL, options?: RequestInit) => {
    const url = typeof resource === 'string' ? resource :
                resource instanceof URL ? resource.toString() : resource.url;

    if (url.includes('/api/auth/session/refresh')) {
      refreshAttemptCount++;
      if (refreshAttemptCount > 1) {
        throw new Error('Duplicate refresh attempt blocked');
      }
    }

    return originalFetch.call(window, resource, options);
  };
};

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) {
    setupFetchInterceptor();
    SuperTokens.init(frontendConfig());
    initialized = true;
    logger.info("SuperTokens initialized");
  }
}
