import type { Graph } from '@api-client/graph/graph/Graph.js'
import type { DomainGraphEdge, DomainGraphNodeType } from './types.js'

/**
 * Recursively removes a node and all its children from the graph.
 * @param key The key of the node to remove.
 */
export function removeGraphNode(graph: Graph<unknown, DomainGraphNodeType, DomainGraphEdge>, key: string): void {
  if (!graph.hasNode(key)) {
    return
  }
  for (const child of graph.children(key)) {
    removeGraphNode(graph, child)
  }
  for (const edge of graph.outEdges(key)) {
    const label = graph.edge(edge)
    if (!label) {
      continue
    }
    // While associations should be associated with the entity through an edge,
    // I am still on a fence about properties being the same...
    // We won't be reusing properties within a domain model.
    if (['property', 'association'].includes(label.type)) {
      removeGraphNode(graph, edge.w)
    }
  }
  graph.removeNode(key)
}
