import { describe, expect, it } from 'vitest' import type { ChatExport, Message } from '@shared/types' import { exportHtml, exportText, inRange, rangeLabel } from '../src/main/export' let nextId = 1 const at = (day: string, hhmm: string): number => new Date(`${day}T${hhmm}`).getTime() const msg = (ts: number, body: string, opts: Partial = {}): Message => ({ id: nextId++, did: '5550000000', contact: '5550001111', direction: 'in', body, ts, kind: 'sms', status: 'delivered', ...opts }) const opts = (o: Partial = {}): ChatExport => ({ format: 'txt', attachments: false, title: 'Aaron', names: {}, ...o }) describe('inRange', () => { const msgs = [ msg(at('2026-10-01', '23:59'), 'a'), msg(at('2026-10-02', '00:00'), 'b'), msg(at('2026-10-03', '12:00'), 'c', { direction: 'out', status: 'failed' }), msg(at('2026-10-04', '23:59'), 'd') ] it('keeps everything but failed sends for all time', () => { expect(inRange(msgs, {}).map((m) => m.body)).toEqual(['a', 'b', 'd']) }) it('includes both end days, in local time', () => { expect(inRange(msgs, { from: '2026-10-02', to: '2026-10-04' }).map((m) => m.body)).toEqual(['b', 'd']) expect(inRange(msgs, { from: '2026-10-01', to: '2026-10-01' }).map((m) => m.body)).toEqual(['a']) }) }) describe('exportText', () => { it('heads each day and lines up continuation lines', () => { const text = exportText( '5550001111', [ msg(at('2026-10-02', '09:05'), 'hi\nthere'), msg(at('2026-10-02', '09:06'), '', { direction: 'out', media: [{ file: 'x.jpg', mime: 'image/jpeg' }] }) ], opts() ) const lines = text.split('\n') expect(lines[0]).toBe('Chat with Aaron ((555) 000-1111)') expect(text).toContain('Friday, October 2, 2026') const first = lines.findIndex((l) => l.endsWith('Aaron: hi')) expect(lines[first + 1]).toBe(' '.repeat(lines[first].indexOf('hi')) + 'there') expect(lines[first + 2]).toMatch(/Me: \[Photo\]$/) }) it('names group senders', () => { const text = exportText( '5550001111,5550002222', [msg(at('2026-10-02', '09:05'), 'yo', { contact: '5550001111,5550002222', sender: '5550002222' })], opts({ title: 'Hike crew', names: { '5550002222': 'Bea' } }) ) expect(text).toContain('Chat with Hike crew\n') expect(text).toContain('Bea: yo') }) }) describe('exportHtml', () => { const m = msg(at('2026-10-02', '09:05'), '&', { media: [{ file: 'x.jpg', mime: 'image/jpeg' }, { file: 'y.m4a', mime: 'audio/mp4' }] }) it('escapes text and shows photos it has, labels for the rest', () => { const html = exportHtml('5550001111', [m], opts({ format: 'pdf' }), (_m, i) => (i === 0 ? 'file:///media/x.jpg' : undefined)) expect(html).toContain('<b>&') expect(html).toContain('') expect(html).toContain('[Audio]') }) }) describe('rangeLabel', () => { it('describes the dates', () => { expect(rangeLabel({})).toBe('All messages') expect(rangeLabel({ from: '2026-10-02', to: '2026-10-02' })).toBe('Oct 2, 2026') expect(rangeLabel({ from: '2026-10-02', to: '2026-10-09' })).toBe('Oct 2, 2026 – Oct 9, 2026') }) })