export const USER_TOKEN_KEY = "web_user_token";

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

  return window.localStorage.getItem(USER_TOKEN_KEY);
}

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

  window.localStorage.setItem(USER_TOKEN_KEY, token);
  const secure = window.location.protocol === "https:" ? "; Secure" : "";
  document.cookie = `${USER_TOKEN_KEY}=${encodeURIComponent(token)}; Path=/; Max-Age=604800; SameSite=Lax${secure}`;
}

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

  window.localStorage.removeItem(USER_TOKEN_KEY);
  document.cookie = `${USER_TOKEN_KEY}=; Path=/; Max-Age=0; SameSite=Lax`;
}

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

  const cookie = document.cookie.split("; ").find((entry) => entry.startsWith(`${USER_TOKEN_KEY}=`));
  if (!cookie) {
    return null;
  }

  return decodeURIComponent(cookie.split("=")[1] ?? "");
}
