import { ResolvedPos } from "prosemirror-model";
import { schema } from "../../schema";

export function canPlaceAttachment($pos: ResolvedPos): boolean {
  return $pos.parent.contentMatchAt($pos.index()).matchType(schema.nodes.at) != null;
}

export function closestAttachmentPlacement($pos: ResolvedPos): ResolvedPos {
  if (canPlaceAttachment($pos)) {
    return $pos;
  }

  // Scan up and forward through the document until reaching a valid location.
  for (let d = $pos.depth; d >= 0; d--) {
    const $cur = $pos.doc.resolve($pos.after(d));
    if (canPlaceAttachment($cur)) {
      return $cur;
    }
  }

  throw new Error("Schema does not support top-level attachments");
}
