import { ADMIN_TOKEN_STORAGE_KEY } from "@/lib/admin-token-constants";
import {
  readAdminTokenFromDocumentCookie,
  writeAdminTokenCookie,
} from "@/lib/admin-token-cookie";

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

  const fromStorage = window.localStorage.getItem(ADMIN_TOKEN_STORAGE_KEY)?.trim();
  if (fromStorage) {
    return fromStorage;
  }

  return readAdminTokenFromDocumentCookie();
}

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

  if (t && t.trim() !== "") {
    const normalized = t.trim();
    window.localStorage.setItem(ADMIN_TOKEN_STORAGE_KEY, normalized);
    writeAdminTokenCookie(normalized);
  } else {
    window.localStorage.removeItem(ADMIN_TOKEN_STORAGE_KEY);
    writeAdminTokenCookie(null);
  }
}
