import { useQuery } from '@tanstack/react-query'
import { sourceFolders, type FolderTreeNode } from '../services/api'

export const FOLDER_TREE_QUERY_KEY = ['folders', 'tree'] as const

export function useFolderTreeQuery() {
  return useQuery<FolderTreeNode[]>({
    queryKey: FOLDER_TREE_QUERY_KEY,
    queryFn: sourceFolders.tree,
    staleTime: 30_000,
  })
}

/** Walk the tree to find a node by id. Used for chip name lookups. */
export function findFolderInTree(
  tree: FolderTreeNode[] | undefined,
  id: string
): FolderTreeNode | null {
  if (!tree) return null
  for (const node of tree) {
    if (node.id === id) return node
    const child = findFolderInTree(node.children, id)
    if (child) return child
  }
  return null
}
