// src/server/features/notes/lib/parser.service.ts
// Parser service for extracting mentions from HTML content

import { loggerService } from '../../../shared/lib/logger';

// Initialize logger
const notesLogger = loggerService.get('HTTP').child({ module: 'parser' });
const logger = loggerService.get('DB').child({ module: 'parser' });

/**
 * Извлечение UUID упоминаний из HTML-формата с тегами <app-mention>
 * Алгоритм:
 * 1. Найти все теги <app-mention user-id="UUID"> в HTML контенте
 * 2. Извлечь UUID из атрибута user-id
 * 3. Вернуть массив UUID для дальнейшей обработки
 *
 * Пример формата: "Пожалуйста, проверьте это <app-mention user-id=\"550e8400-e29b-41d4-a716-446655440000\" user-name=\"Иван Иванов\">Иван Иванов</app-mention>"
 */
export async function parseMentions(content: string): Promise<string[]> {
  try {
    notesLogger.debug(`[MENTIONS] Checking HTML content: "${content}"`);

    // Шаг 1: Извлечь все UUID из контента по паттерну <app-mention user-id="UUID">
    // UUID format: 8-4-4-4-12 hex digits
    const uuidPattern = /user-id="([a-f0-9-]{36})"/gi;
    const matches = [...content.matchAll(uuidPattern)];

    notesLogger.debug(`[MENTIONS] Found ${matches.length} mention tags in HTML`);

    if (matches.length === 0) {
      notesLogger.debug('[MENTIONS] No mention tags found, returning empty array');
      return [];
    }

    // Шаг 2: Извлечь UUID из каждого совпадения
    const mentionedIds = matches.map(match => match[1]);

    // Удалить дубликаты (используем Set)
    const uniqueIds = Array.from(new Set(mentionedIds));

    notesLogger.debug(`[MENTIONS] Extracted ${uniqueIds.length} unique UUIDs:`, uniqueIds);

    return uniqueIds;
  } catch (error) {
    logger.error('Error parsing mentions:', error);
    notesLogger.error('[MENTIONS] Error:', error);
    return [];
  }
}
