import { contactMessagesAdapter } from '@/lib/adapters/contacts';
import { logger } from '@/lib/logger';

export interface CreateInboundMessageInput {
  contactId: string;
  fromEmail: string;
  toEmail: string;
  bodyHtml: string;
  bodyText?: string;
  receivedAt?: Date;
}

export interface CreateOutboundMessageInput {
  contactId: string;
  fromEmail: string;
  toEmail: string;
  ccEmails?: string[];
  subject?: string;
  bodyHtml: string;
  bodyText?: string;
  attachments?: Array<{
    filename: string;
    url: string;
    size: number;
    mimeType: string;
  }>;
  sentBy?: string;
  messageId?: string;
}

export async function getContactMessages(contactId: string) {
  return contactMessagesAdapter.findMany({
    where: { contactId },
    orderBy: { createdAt: 'asc' },
  });
}

export async function createInboundMessage(input: CreateInboundMessageInput) {
  try {
    const now = new Date();
    const createdAt = input.receivedAt ?? now;

    return await contactMessagesAdapter.create({
      data: {
        contactId: input.contactId,
        direction: 'inbound',
        fromEmail: input.fromEmail,
        toEmail: input.toEmail,
        bodyHtml: input.bodyHtml,
        bodyText: input.bodyText ?? null,
        status: 'sent',
        createdAt,
        updatedAt: now,
      },
    });
  } catch (error) {
    logger.error('Failed to create inbound contact message', { error });
    throw error;
  }
}

export async function createOutboundMessage(input: CreateOutboundMessageInput) {
  try {
    const now = new Date();
    return await contactMessagesAdapter.create({
      data: {
        contactId: input.contactId,
        direction: 'outbound',
        fromEmail: input.fromEmail,
        toEmail: input.toEmail,
        ccEmails: input.ccEmails ?? [],
        subject: input.subject ?? null,
        bodyHtml: input.bodyHtml,
        bodyText: input.bodyText ?? null,
        attachments: input.attachments ?? [],
        sentBy: input.sentBy ?? null,
        messageId: input.messageId ?? null,
        status: 'sent',
        createdAt: now,
        updatedAt: now,
      },
    });
  } catch (error) {
    logger.error('Failed to create outbound contact message', { error });
    throw error;
  }
}
