import { internal } from '../../../../_generated/api';
import type { Id } from '../../../../_generated/dataModel';
import type { ActionCtx } from '../../../../_generated/server';
import { buildEmailMetadata } from './build_email_metadata';
import type { EmailType } from './types';

/**
 * Add a message to an existing conversation
 */
export async function addMessageToConversation(
  ctx: ActionCtx,
  conversationId: Id<'conversations'>,
  organizationId: string,
  email: EmailType,
  isCustomer: boolean,
  status: 'delivered' | 'sent',
  integrationName?: string,
) {
  const emailTimestamp = new Date(email.date).getTime();

  await ctx.runMutation(
    internal.conversations.internal_mutations.addMessageToConversation,
    {
      conversationId,
      organizationId,
      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 } : {}),
    },
  );
}
