/**
 * Run-context helpers. The active run is carried in the `?run=` search param;
 * "latest" (the default, no param) resolves server-side to the newest
 * indexed run.
 */
import { useCallback } from "react";
import { useSearchParams } from "react-router-dom";

export const LATEST_RUN = "latest";

/** The run id to use in API paths ("latest" when no explicit selection). */
export function useRunId(): string {
  const [searchParams] = useSearchParams();
  return searchParams.get("run") ?? LATEST_RUN;
}

/** Raw `?run=` value (null when following latest). */
export function useRunParam(): string | null {
  const [searchParams] = useSearchParams();
  return searchParams.get("run");
}

/**
 * Returns a function that sets (or clears, for "latest") the `?run=` param
 * while preserving the other current search params.
 */
export function useSetRunParam(): (runId: string | null) => void {
  const [searchParams, setSearchParams] = useSearchParams();
  return useCallback(
    (runId: string | null) => {
      const next = new URLSearchParams(searchParams);
      if (runId === null || runId === LATEST_RUN) {
        next.delete("run");
      } else {
        next.set("run", runId);
      }
      setSearchParams(next, { preventScrollReset: true });
    },
    [searchParams, setSearchParams],
  );
}

/** Append the current run param to a path that already carries a query string. */
export function withRunParam(path: string, runId: string): string {
  if (runId === LATEST_RUN) return path;
  const sep = path.includes("?") ? "&" : "?";
  return `${path}${sep}run=${encodeURIComponent(runId)}`;
}
