/** Resolve the active run record for the current `?run=` context. */
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { ApiError } from "../api/client";
import { getRun } from "../api/service";
import type { RunRecord } from "../api/schemas";
import { LATEST_RUN, useRunId } from "./run";

export function useRun(): { runId: string; runQuery: UseQueryResult<RunRecord> } {
  const runId = useRunId();
  const runQuery = useQuery({
    queryKey: ["run", runId],
    queryFn: () => getRun(runId),
    staleTime: 60_000,
  });
  return { runId, runQuery };
}

/**
 * Run-aware title for the run-scope error gate: a 404 means the requested
 * run does not exist; anything else is a service/transport failure.
 */
export function runErrorTitle(runId: string, error: unknown): string {
  if (error instanceof ApiError && error.status === 404) {
    return runId === LATEST_RUN
      ? "No indexed run available yet"
      : `Run ${runId} does not exist`;
  }
  return `Failed to load run ${runId}`;
}
