import { createServerFn } from "@tanstack/react-start";

const fetchOrigin = createServerFn({ method: "GET" }).handler(async () => {
  const { getRequest } = await import("@tanstack/react-start/server");
  return new URL(getRequest().url).origin;
});

/**
 * Origin of the running site, derived dynamically. On the server it reads the
 * incoming request URL; in the browser it reads location. Never hardcoded.
 */
export async function currentOrigin(): Promise<string> {
  if (typeof window !== "undefined") {
    return window.location.origin;
  }
  return fetchOrigin();
}
