import type { MessageEnvelope, Address } from '@shared/types/message' // imapflow BodyStructure type export interface ImapBodyPart { part?: string type?: string subtype?: string disposition?: string parameters?: Record id?: string encoding?: string childNodes?: ImapBodyPart[] } interface ImapFetchedMessage { uid: number envelope?: { subject?: string from?: Array<{ name?: string; address?: string }> to?: Array<{ name?: string; address?: string }> cc?: Array<{ name?: string; address?: string }> date?: Date messageId?: string inReplyTo?: string } flags?: Set bodyStructure?: ImapBodyPart } function addressesFrom(list?: Array<{ name?: string; address?: string }>): Address[] { return (list ?? []).map((a) => ({ name: a.name ?? '', email: a.address ?? '' })) } function messageHasAttachments(node?: ImapBodyPart): boolean { if (!node) return false if (node.disposition === 'attachment') return true if (node.childNodes) return node.childNodes.some((c) => messageHasAttachments(c)) return false } export function convertImapMessage(msg: unknown, folderId: string): MessageEnvelope { const m = msg as ImapFetchedMessage const flags = m.flags ?? new Set() return { id: String(m.uid), folderId, subject: m.envelope?.subject ?? '(no subject)', from: addressesFrom(m.envelope?.from)[0] ?? { name: '', email: '' }, to: addressesFrom(m.envelope?.to), cc: addressesFrom(m.envelope?.cc), date: m.envelope?.date?.toISOString() ?? new Date().toISOString(), flags: { seen: flags.has('\\Seen'), flagged: flags.has('\\Flagged'), answered: flags.has('\\Answered'), deleted: flags.has('\\Deleted') }, hasAttachments: messageHasAttachments(m.bodyStructure), snippet: '', messageId: m.envelope?.messageId ?? undefined, inReplyTo: m.envelope?.inReplyTo ?? undefined, } }