import type { FolderTreeNode } from "@/lib/sidebar-nav-data"

/** Retourne les ids des parents à ouvrir pour afficher `targetId`, ou null. */
export function ancestorFolderIdsForTarget(
  nodes: FolderTreeNode[],
  targetId: string,
  chain: string[] = []
): string[] | null {
  for (const n of nodes) {
    if (n.id === targetId) return chain
    if (n.children?.length) {
      const found = ancestorFolderIdsForTarget(n.children, targetId, [
        ...chain,
        n.id,
      ])
      if (found) return found
    }
  }
  return null
}

export function folderSubtreeContainsId(
  node: FolderTreeNode,
  targetId: string
): boolean {
  if (node.id === targetId) return true
  return node.children?.some((c) => folderSubtreeContainsId(c, targetId)) ?? false
}

export function findFolderNodeById(
  tree: FolderTreeNode[],
  id: string
): FolderTreeNode | null {
  for (const node of tree) {
    if (node.id === id) return node
    if (node.children?.length) {
      const hit = findFolderNodeById(node.children, id)
      if (hit) return hit
    }
  }
  return null
}

export function folderNodeExists(tree: FolderTreeNode[], id: string): boolean {
  return findFolderNodeById(tree, id) != null
}
