import type { ContentBlock } from '../db/schema.js';

/** Извлекает поисковый текст из блоков контента */
export function blocksToSearchText(blocks: ContentBlock[] | null): string {
  if (!blocks || !Array.isArray(blocks)) return '';
  return blocks
    .map((b) => {
      if (b.type === 'text' && b.data?.html) return stripHtml(String(b.data.html));
      if (b.type === 'heading' && b.data?.text) return b.data.text;
      if (b.type === 'image' && b.data?.caption) return b.data.caption;
      if (b.type === 'video' && b.data?.caption) return b.data.caption;
      if (b.type === 'audio' && b.data?.caption) return b.data.caption;
      if (b.type === 'table' && b.data?.html) return stripHtml(String(b.data.html));
      return '';
    })
    .filter(Boolean)
    .join(' ');
}

function stripHtml(html: string): string {
  return html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
}
