import type { Node as ProseMirrorNode } from "@tiptap/pm/model"

export function isDocsBlockType(typeName: string): boolean {
  return typeName === "paragraph" || typeName === "heading"
}

export function getDocsBlockTargets(
  doc: ProseMirrorNode,
  from: number,
  to: number
): Array<{ pos: number; node: ProseMirrorNode }> {
  const targets: Array<{ pos: number; node: ProseMirrorNode }> = []

  if (from === to) {
    const $pos = doc.resolve(from)
    for (let depth = $pos.depth; depth > 0; depth -= 1) {
      const node = $pos.node(depth)
      if (isDocsBlockType(node.type.name)) {
        targets.push({ pos: $pos.before(depth), node })
        break
      }
    }
    return targets
  }

  doc.nodesBetween(from, to, (node, pos) => {
    if (!isDocsBlockType(node.type.name)) return
    targets.push({ pos, node })
  })

  return targets
}
