import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";
import { TypeInput } from "supertokens-node/types";
import Dashboard from "supertokens-node/recipe/dashboard";
import UserRoles from "supertokens-node/recipe/userroles";
import { appInfo } from "./config";
import PasswordlessDevelopmentMode from "./recipes/passwordless-development-mode";
import { logger } from "./";
import PasswordlessTwilioVerify from "./recipes/passwordless-twilio-verify";

export const backendConfig = (): TypeInput => {
  return {
    framework: "custom",
    supertokens: {
      connectionURI:
        process.env.SUPERTOKENS_URI || "https://try.supertokens.io",
    },
    appInfo,
    recipeList: [
      //PasswordlessTwilioVerify.init(),
      PasswordlessDevelopmentMode.init(),
      Session.init({
        cookieSameSite: "lax",
        cookieSecure: import.meta.env.NODE_ENV === "production",
        cookieDomain:
          import.meta.env.NODE_ENV === "production" ? ".example.com" : undefined,
        antiCsrf: import.meta.env.NODE_ENV === "production" ? "VIA_TOKEN" : "NONE",

        // Debug only
        exposeAccessTokenToFrontendInCookieBasedAuth: true,
      }),
      Dashboard.init(),
      UserRoles.init(),
    ],
    telemetry: import.meta.env.NODE_ENV !== "production",
  };
};

let initialized = false;
export function ensureSuperTokensBackend() {
  if (!initialized && typeof window === 'undefined') {
    SuperTokens.init(backendConfig());
    initialized = true;
    logger.simple("Backend initialized");
  }
}
