/**
 * Tiptap JSONB plain-text extractor — tenant-public-api (wave-11 leaf-D).
 * Flattens Tiptap document JSONB to plain text for task.description_text.
 * Never exposes raw JSONB to API consumers.
 */

interface TiptapNode {
  type?: string
  text?: string
  content?: TiptapNode[]
}

function extractText(node: TiptapNode): string {
  if (node.text) return node.text
  if (node.content) return node.content.map(extractText).join(' ')
  return ''
}

export function extractPlainText(doc: unknown): string | null {
  if (!doc || typeof doc !== 'object') return null
  try {
    const text = extractText(doc as TiptapNode).replace(/\s+/g, ' ').trim()
    return text || null
  } catch {
    return null
  }
}
