import { Node, mergeAttributes } from "@tiptap/core"

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    image: {
      /** 插入图片(绑定 fileAttachments 的 fileId) */
      setImage: (attrs: { src: string; fileId?: string; alt?: string }) => ReturnType
    }
  }
}

/**
 * 图片节点 —— 自实现(不依赖 @tiptap/extension-image)。
 * 存储 src + fileId(关联 fileAttachments 表),用于书签图、宣传照等图片附件。
 */
export const ImageNode = Node.create({
  name: "image",
  group: "block",
  draggable: true,
  addAttributes() {
    return {
      src: {
        default: null,
        parseHTML: (el) => el.getAttribute("src") || "",
      },
      alt: {
        default: null,
        parseHTML: (el) => el.getAttribute("alt"),
        renderHTML: (attrs) => (attrs.alt ? { alt: attrs.alt } : {}),
      },
      fileId: {
        default: null,
        parseHTML: (el) => el.getAttribute("data-file-id"),
        renderHTML: (attrs) =>
          attrs.fileId ? { "data-file-id": attrs.fileId } : {},
      },
    }
  },
  parseHTML: () => [{ tag: "img[src]" }],
  renderHTML: ({ HTMLAttributes }) => ["img", mergeAttributes(HTMLAttributes)],
  addCommands() {
    return {
      setImage:
        (attrs) =>
        ({ commands }) =>
          commands.insertContent({ type: "image", attrs }),
    }
  },
})
