export const DEFAULT_OIDC_SCOPE = "openid offline_access profile email";
export const DEFAULT_OIDC_REDIRECT_PATH = "/auth/callback";

export type CommonOidcConfigOptions<TUserStore = unknown> = {
  authority: string;
  clientId: string;
  origin?: string;
  redirectPath?: string;
  scope?: string;
  automaticSilentRenew?: boolean;
  userStore: TUserStore;
};

export type LoginRedirectGuardParams = {
  pathname: string;
  isRedirecting: boolean;
  loginPath?: string;
  callbackPath?: string;
};

type CommonOidcRuntimeConfig<TUserStore> = {
  authority: string;
  client_id: string;
  redirect_uri: string;
  response_type: "code";
  scope: string;
  post_logout_redirect_uri: string;
  popup_redirect_uri: string;
  userStore: TUserStore;
  automaticSilentRenew: boolean;
};

export function buildCommonOidcRuntimeConfig<TUserStore>({
  authority,
  clientId,
  origin = window.location.origin,
  redirectPath = DEFAULT_OIDC_REDIRECT_PATH,
  scope = DEFAULT_OIDC_SCOPE,
  automaticSilentRenew = false,
  userStore,
}: CommonOidcConfigOptions<TUserStore>): CommonOidcRuntimeConfig<TUserStore> {
  const callbackUrl = `${origin}${redirectPath}`;

  return {
    authority,
    client_id: clientId,
    redirect_uri: callbackUrl,
    response_type: "code",
    scope,
    post_logout_redirect_uri: origin,
    popup_redirect_uri: callbackUrl,
    userStore,
    automaticSilentRenew,
  };
}

export function buildCommonUserManagerSettings<
  TConfig extends {
    authority?: string;
    client_id?: string;
    redirect_uri?: string;
  },
>(config: TConfig) {
  return {
    ...config,
    authority: config.authority || "",
    client_id: config.client_id || "",
    redirect_uri: config.redirect_uri || "",
  };
}

export function shouldStartLoginRedirect({
  pathname,
  isRedirecting,
  loginPath = "/login",
  callbackPath = DEFAULT_OIDC_REDIRECT_PATH,
}: LoginRedirectGuardParams) {
  if (isRedirecting) {
    return false;
  }

  if (pathname === loginPath || pathname.startsWith(callbackPath)) {
    return false;
  }

  return true;
}
