import { useQuery } from "@tanstack/react-query";

import { getBackendBaseURL } from "../config";

export type ReferenceFileInfo = {
  filename: string;
  size: string;
  virtual_path: string;
  artifact_url: string;
  source: "artifact" | "upload";
};

type ListReferenceFilesResponse = {
  files: ReferenceFileInfo[];
  count: number;
};

async function listReferenceFiles(
  threadId: string,
): Promise<ListReferenceFilesResponse> {
  const response = await fetch(
    `${getBackendBaseURL()}/api/threads/${threadId}/artifacts/list`,
  );
  if (!response.ok) {
    throw new Error("Failed to list reference files");
  }
  return response.json();
}

export function useReferenceFiles(threadId: string | undefined) {
  return useQuery({
    queryKey: ["references", "list", threadId],
    queryFn: () => listReferenceFiles(threadId ?? ""),
    enabled: Boolean(threadId),
    refetchOnWindowFocus: false,
  });
}
