import { buildEmailMetadata } from './build_email_metadata';
import type { EmailType } from './types';

/**
 * Build initial message object for conversation creation
 */
export function buildInitialMessage(
  email: EmailType,
  isCustomer: boolean,
  status: 'delivered' | 'sent',
  integrationName?: string,
) {
  const emailTimestamp = new Date(email.date).getTime();

  return {
    sender: email.from?.[0]?.address || email.from?.[0]?.name || 'unknown',
    content: email.html || email.text || '',
    isCustomer,
    status,
    externalMessageId: email.messageId,
    metadata: buildEmailMetadata(email),
    sentAt: emailTimestamp,
    deliveredAt: status === 'delivered' ? emailTimestamp : undefined,
    ...(email.attachments?.length ? { attachments: email.attachments } : {}),
    ...(integrationName ? { integrationName } : {}),
  };
}
