export interface CommentMentionMember {
  id: string;
  name: string;
}

export interface MergeMentionMemberIdsInput {
  content: string;
  explicitMemberIds: string[];
  members: CommentMentionMember[];
}

export function extractMentionNames(content: string): string[] {
  const names: string[] = [];
  const pattern = /@([\p{L}\p{N}_\-.]+)/gu;
  for (const match of content.matchAll(pattern)) {
    if (match[1]) names.push(match[1]);
  }
  return names;
}

export function mergeMentionMemberIds(input: MergeMentionMemberIdsInput): string[] {
  const ids = new Set<string>();
  const names = new Set(extractMentionNames(input.content).map(normalizeName));
  for (const member of input.members) {
    if (names.has(normalizeName(member.name))) ids.add(member.id);
  }
  for (const id of input.explicitMemberIds) {
    const normalized = id.trim();
    if (normalized) ids.add(normalized);
  }
  return Array.from(ids);
}

function normalizeName(name: string): string {
  return name.trim().toLowerCase();
}
