import { resetAuthExpiredNotification } from "./authEvents";

export const DMS_ACCESS_TOKEN_KEY = "dms.accessToken";

type StorageKind = "session" | "local";

function getStorage(kind: StorageKind): Storage | null {
  try {
    return kind === "session"
      ? globalThis.sessionStorage
      : globalThis.localStorage;
  } catch {
    return null;
  }
}

function read(storage: Storage | null): string | null {
  try {
    return storage?.getItem(DMS_ACCESS_TOKEN_KEY) ?? null;
  } catch {
    return null;
  }
}

function remove(storage: Storage | null): void {
  try {
    storage?.removeItem(DMS_ACCESS_TOKEN_KEY);
  } catch {
    // Storage can be unavailable in privacy-restricted browser contexts.
  }
}

export const tokenStore = {
  getAccessToken(): string | null {
    return read(getStorage("session")) ?? read(getStorage("local"));
  },

  saveAccessToken(accessToken: string, keepSignedIn: boolean): void {
    this.clearAccessToken();
    const storage = getStorage(keepSignedIn ? "local" : "session");
    storage?.setItem(DMS_ACCESS_TOKEN_KEY, accessToken);
    resetAuthExpiredNotification();
  },

  clearAccessToken(): void {
    remove(getStorage("session"));
    remove(getStorage("local"));
  },
};
