export const PORTAL_SESSION_STORAGE_KEY = "powerup.portal.session-token";
export const PORTAL_ADMIN_SESSION_STORAGE_KEY = "powerup.portal.admin-session-token";

export function getStoredSessionToken(): string | null {
  if (typeof window === "undefined") {
    return null;
  }

  const token = window.localStorage.getItem(PORTAL_SESSION_STORAGE_KEY)?.trim();
  return token || null;
}

export function storeSessionToken(token: string): void {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.setItem(PORTAL_SESSION_STORAGE_KEY, token);
}

export function clearSessionToken(): void {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(PORTAL_SESSION_STORAGE_KEY);
}

export function getStoredAdminSessionToken(): string | null {
  if (typeof window === "undefined") {
    return null;
  }

  const token = window.localStorage.getItem(PORTAL_ADMIN_SESSION_STORAGE_KEY)?.trim();
  return token || null;
}

export function storeAdminSessionToken(token: string): void {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.setItem(PORTAL_ADMIN_SESSION_STORAGE_KEY, token);
}

export function clearAdminSessionToken(): void {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(PORTAL_ADMIN_SESSION_STORAGE_KEY);
}

export function appendSessionToUrl(url: string): string {
  if (typeof window === "undefined") {
    return url;
  }

  const token = getStoredSessionToken();
  if (!token) {
    return url;
  }

  try {
    const parsedUrl = new URL(url, window.location.origin);
    parsedUrl.searchParams.set("session", token);
    return parsedUrl.toString();
  } catch {
    return url;
  }
}
