import { UserManager, WebStorageStateStore } from "oidc-client-ts";
import type { AuthProviderProps } from "react-oidc-context";
import {
  buildCommonOidcRuntimeConfig,
  buildCommonUserManagerSettings,
} from "../../../common/core/auth";
import { resolveAdminPublicOrigin } from "./authConfig";

const adminPublicOrigin = resolveAdminPublicOrigin(
  import.meta.env.VITE_ADMIN_PUBLIC_URL,
  window.location.origin,
);

export const oidcConfig: AuthProviderProps = buildCommonOidcRuntimeConfig({
  authority: import.meta.env.VITE_OIDC_AUTHORITY || "https://sso.hmac.kr/oidc",
  clientId: import.meta.env.VITE_OIDC_CLIENT_ID || "adminfront",
  origin: adminPublicOrigin,
  userStore: new WebStorageStateStore({ store: window.localStorage }),
});

export const userManager = new UserManager(
  buildCommonUserManagerSettings(oidcConfig),
);

export function clearStoredAdminAuthSession(
  storage: Storage = window.localStorage,
) {
  const keysToRemove: string[] = [];

  for (let index = 0; index < storage.length; index += 1) {
    const key = storage.key(index);
    if (
      key &&
      (key === "admin_session" ||
        key.startsWith("oidc.user:") ||
        key.startsWith("oidc.state") ||
        key.startsWith("oidc.signin"))
    ) {
      keysToRemove.push(key);
    }
  }

  for (const key of keysToRemove) {
    storage.removeItem(key);
  }
}

export async function clearAdminAuthSession() {
  clearStoredAdminAuthSession();
  await userManager.removeUser();
}
