import MailComposer from "nodemailer/lib/mail-composer/index.js";
import type { MailboxConfig } from "../config.js";
import type { ComposeMessage } from "./schemas.js";

export type BuiltMessage = {
  raw: Buffer;
  envelope: {
    from: string;
    to: string[];
  };
  messageId: string;
};

export async function buildRawMessage(
  mailbox: MailboxConfig,
  message: ComposeMessage,
  mode: "draft" | "send",
): Promise<BuiltMessage> {
  const compiled = new MailComposer({
    from: { name: mailbox.label, address: mailbox.address },
    to: message.to,
    cc: message.cc.length ? message.cc : undefined,
    bcc: message.bcc.length ? message.bcc : undefined,
    subject: message.subject,
    text: message.text,
    ...(message.in_reply_to ? { inReplyTo: message.in_reply_to } : {}),
    ...(message.references.length ? { references: message.references } : {}),
    date: new Date(),
  }).compile();
  compiled.keepBcc = mode === "draft";
  compiled.newline = "windows";
  const envelope = compiled.getEnvelope();
  const messageId = compiled.messageId();
  const raw = await compiled.build();

  return {
    raw,
    envelope: {
      from: mailbox.address,
      to: [...message.to, ...message.cc, ...message.bcc],
    },
    messageId,
  };
}
