/**
 * TipTap suggestion configuration for @mentions and /commands.
 */

import type { Editor, Range } from '@tiptap/core';
import type { SuggestionOptions } from '@tiptap/suggestion';
import type { MentionItem } from './types';

/**
 * Creates a suggestion config for the given trigger character.
 * The `items` function should be injected with room context.
 * Note: `editor` is injected by TipTap at runtime, so we cast to bypass TS requirement.
 */
export function createSuggestionConfig(
  trigger: string,
  getItems: (query: string) => MentionItem[],
) {
  return {
    char: trigger,
    allowSpaces: false,
    items: ({ query }: { query: string }) => getItems(query),
    command: ({ editor, range, props }: { editor: Editor; range: Range; props: MentionItem }) => {
      editor
        .chain()
        .focus()
        .deleteRange(range)
        .insertContent({
          type: 'mention',
          attrs: {
            id: props.id,
            label: props.label,
            type: props.type,
          },
        })
        .insertContent(' ')
        .run();
    },
  } as unknown as Omit<SuggestionOptions<MentionItem>, 'render'>;
}
