import { isDocumentOfType, messageToDocument, type ThreadItem, type UnknownDocument } from '../types/index.ts' export function formatThreadItemPreview(item: ThreadItem): string { return formatDocumentPreview(messageToDocument(item)) } export function formatDocumentPreview(document: UnknownDocument): string { if (isDocumentOfType(document, 'text/plain')) { return document.value } if (isDocumentOfType(document, 'application/vnd.lime.media-link+json')) { return `[media] ${document.value.title || document.value.text || document.value.uri}` } if (isDocumentOfType(document, 'application/vnd.lime.web-link+json')) { return `[link] ${document.value.text}` } if (isDocumentOfType(document, 'application/vnd.lime.reply+json')) { return formatDocumentPreview(document.value.replied) } if (isDocumentOfType(document, 'application/vnd.iris.ticket+json')) { return `[ticket #${document.value.sequentialId}]` } if (isDocumentOfType(document, 'application/vnd.lime.select+json')) { const options = document.value.options.map((option) => option.text).join(' | ') return `[select] ${document.value.text} [select-options] ${options}` } if (isDocumentOfType(document, 'application/json')) { const value = document.value if ( value.type === 'template' && value.template && typeof value.template === 'object' && 'name' in value.template ) { return `[whatsapp template: ${value.template.name as string}]` } if (value.type === 'interactive' && value.interactive && typeof value.interactive === 'object') { return interactiveToHumanReadable(value.interactive as Record) } } return `[${document.type}]` } function interactiveToHumanReadable(interactive: Record): string { const parts: Array = [] const header = interactive.header as { type?: string; text?: string } | undefined if (header?.type === 'text' && header.text) { parts.push(header.text) } const body = interactive.body as { text?: string } | undefined if (body?.text) { parts.push(body.text) } const footer = interactive.footer as { text?: string } | undefined if (footer?.text) { parts.push(footer.text) } const action = interactive.action as | { name: 'cta_url' parameters: { display_text: string } } | { name: 'flow' parameters: { flow_cta: string } } | { buttons: Array<{ type: 'reply' reply: { id: string; title: string } }> } | { sections: Array<{ rows?: Array<{ title: string }> }> } | undefined if (!action) { return parts.join('\n') } if ('buttons' in action) { const items = action.buttons .filter((button) => button.type === 'reply') .map((button) => button.reply.title) .join('') if (items) { parts.push(items) } } else if ('sections' in action) { const items = action.sections.flatMap((section) => section.rows?.map((row) => row.title) ?? []).join('') if (items) { parts.push(items) } } else if (action.name === 'cta_url') { parts.push(`Link: ${action.parameters.display_text}`) } else if (action.name === 'flow') { parts.push(`Flow: ${action.parameters.flow_cta}`) } return parts.join('\n') }