/**
 * @bobfrankston/mailx-compose
 * Compose message logic — builds prefilled compose data for reply/forward.
 * UI lives in client/compose/; this package has the shared logic.
 */

import type { Message, EmailAddress, ComposeMessage } from "@bobfrankston/mailx-types";

export type ComposeMode = "new" | "reply" | "replyAll" | "forward";

/** Data passed to the compose window via query params or postMessage */
export interface ComposeInit {
    mode: ComposeMode;
    accountId: string;
    to: EmailAddress[];
    cc: EmailAddress[];
    subject: string;
    bodyHtml: string;
    inReplyTo: string;
    references: string[];
}

/** Build compose init data from an original message and mode */
export function buildComposeInit(mode: ComposeMode, accountId: string, original?: Message): ComposeInit {
    const init: ComposeInit = {
        mode,
        accountId,
        to: [],
        cc: [],
        subject: "",
        bodyHtml: "",
        inReplyTo: "",
        references: [],
    };

    if (!original) return init;

    const rePrefix = /^(re|fwd?):\s*/i;
    const cleanSubject = original.subject.replace(rePrefix, "");

    switch (mode) {
        case "reply":
            init.to = [original.from];
            init.subject = `Re: ${cleanSubject}`;
            init.bodyHtml = quoteBody(original);
            init.inReplyTo = original.messageId;
            init.references = [...original.references, original.messageId];
            break;

        case "replyAll":
            init.to = [original.from, ...original.to.filter(a => a.address !== original.from.address)];
            init.cc = original.cc || [];
            init.subject = `Re: ${cleanSubject}`;
            init.bodyHtml = quoteBody(original);
            init.inReplyTo = original.messageId;
            init.references = [...original.references, original.messageId];
            break;

        case "forward":
            init.subject = `Fwd: ${cleanSubject}`;
            init.bodyHtml = forwardBody(original);
            break;
    }

    return init;
}

// Plain-text quoting uses `white-space:pre-wrap` so original line breaks
// survive but long lines still wrap to the viewport. `<pre>` (the prior
// approach) was honest about line breaks but disabled wrapping entirely,
// producing horizontal-scroll quotes that broke the compose layout.
const PLAIN_QUOTE_STYLE = "white-space:pre-wrap;font-family:inherit;margin:0";

function quoteBody(msg: Message): string {
    const date = new Date(msg.date).toLocaleString();
    const from = msg.from.name ? `${msg.from.name} <${msg.from.address}>` : msg.from.address;
    const body = msg.bodyHtml || `<div style="${PLAIN_QUOTE_STYLE}">${escapeHtml(msg.bodyText)}</div>`;
    return `<br><div class="reply"><p>On ${date}, ${escapeHtml(from)} wrote:</p><blockquote>${body}</blockquote></div>`;
}

function forwardBody(msg: Message): string {
    const date = new Date(msg.date).toLocaleString();
    const from = msg.from.name ? `${msg.from.name} <${msg.from.address}>` : msg.from.address;
    const to = msg.to.map(a => a.name ? `${a.name} <${a.address}>` : a.address).join(", ");
    const body = msg.bodyHtml || `<div style="${PLAIN_QUOTE_STYLE}">${escapeHtml(msg.bodyText)}</div>`;
    return `<br><div class="reply"><p>---------- Forwarded message ----------<br>From: ${escapeHtml(from)}<br>Date: ${date}<br>Subject: ${escapeHtml(msg.subject)}<br>To: ${escapeHtml(to)}</p>${body}</div>`;
}

function escapeHtml(s: string): string {
    return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
