import { useInfiniteQuery } from "@tanstack/react-query"; import { ApiClientError } from "@/services/api-client"; import { listOssObjects, type OssListFile, type OssListFolder, type OssListPage, } from "@/services/oss"; interface UseOssListOptions { prefix: string; search?: string; /** When false, pauses fetching — useful while the parent tab is hidden. */ enabled?: boolean; } export interface UseOssListResult { folders: OssListFolder[]; files: OssListFile[]; isLoading: boolean; isFetchingNextPage: boolean; hasNextPage: boolean; fetchNextPage: () => void; refetch: () => void; error: Error | null; /** Cast back to ApiClientError when present, so the UI can read displayMessage / upstream details. */ apiError: ApiClientError | null; /** Forwarded so the UI can render the "OSS_FORBIDDEN / NOT_CONFIGURED" state. */ errorCode: string | null; } const PAGE_SIZE = 100; /** * Query key shape mirrors `lib/query-keys.ts` conventions: a stable string * head plus the variable identifiers. Co-located with the hook because no * other module needs to invalidate this cache (the page is read-only). */ function queryKey(prefix: string, search: string) { return ["oss-list", prefix, search] as const; } export function useOssList(options: UseOssListOptions): UseOssListResult { const { prefix, search = "", enabled = true } = options; const query = useInfiniteQuery({ queryKey: queryKey(prefix, search), queryFn: ({ pageParam }) => listOssObjects({ prefix, continuationToken: typeof pageParam === "string" ? pageParam : undefined, maxResults: PAGE_SIZE, search: search || undefined, }), getNextPageParam: (last) => last.nextContinuationToken ?? undefined, initialPageParam: undefined, enabled, // Listings are invalidated by re-mounting the dialog, not by mutations. staleTime: 30_000, refetchOnWindowFocus: false, }); const folders: OssListFolder[] = []; const files: OssListFile[] = []; for (const page of query.data?.pages ?? []) { folders.push(...page.folders); files.push(...page.files); } const apiError = query.error instanceof ApiClientError ? query.error : null; const errorCode = apiError ? apiError.code : null; return { folders, files, isLoading: query.isLoading, isFetchingNextPage: query.isFetchingNextPage, hasNextPage: Boolean(query.hasNextPage), fetchNextPage: () => { if (query.hasNextPage && !query.isFetchingNextPage) query.fetchNextPage(); }, refetch: () => { void query.refetch(); }, error: query.error ?? null, apiError, errorCode, }; }