import Image from '@tiptap/extension-image';

/**
 * PC 输入框专用的 CustomImage 扩展
 * - 支持 class：Normal（普通图片）/ File（文件卡片缩略图）/ Emoji（表情）
 * - 额外携带 originUrl，用于图片/视频快捷回复保留原始 CDN 地址
 * - renderHTML 时把 class 前缀化为 custom-image-Normal / custom-image-File / custom-image-Emoji
 */
export default Image.extend({
  name: 'custom-image',

  addAttributes() {
    return {
      ...(Image.config as any).addAttributes(),
      class: {
        default: 'Normal',
        rendered: false,
      },
      originUrl: {
        default: '',
        rendered: false,
      },
    };
  },

  addCommands() {
    return {
      setImage:
        (options: Record<string, any>) =>
        ({ tr, commands }: any) => {
          if ((tr.selection as any)?.node?.type?.name === 'custom-image') {
            return commands.updateAttributes('custom-image', options);
          }
          return commands.insertContent({
            type: this.name,
            attrs: options,
          });
        },
    } as any;
  },

  renderHTML({ node, HTMLAttributes }) {
    const rawClass = (node.attrs.class as string) || 'Normal';
    HTMLAttributes.class = rawClass.startsWith('custom-image-')
      ? rawClass
      : `custom-image-${rawClass}`;
    return ['img', HTMLAttributes];
  },
});
