/**
 * Inline-image extraction for outgoing mail.
 *
 * The compose editors embed pasted/inlined images as `data:` URIs — that's
 * what renders inside a WebView editor with no server round-trip. But a
 * `data:` URI inside the text/html MIME part is NOT interoperable mail:
 * Outlook desktop (Word renderer) doesn't render data: images at all, and
 * Gmail's web sanitizer strips them, so recipients on the two biggest
 * platforms see broken/missing images while Thunderbird/Apple Mail users see
 * the message fine. The interoperable form is RFC 2392 `cid:` references to
 * base64 image parts inside a multipart/related wrapper — what every mail
 * client has emitted since the 90s.
 *
 * This helper rewrites `<img src="data:...;base64,...">` to `cid:` refs and
 * hands back the extracted parts; the platform send() paths (desktop
 * mailx-service and Android/web web-service) wrap them into
 * multipart/related. Shared here (mailx-types, zero deps) so both MIME
 * assemblers can't drift apart.
 *
 * Non-base64 data: URIs (utf8 SVG etc.) are left in place — rare, small,
 * and rewriting them would mean re-encoding; the size/interop problem this
 * solves comes from pasted photos, which are always base64.
 */

export interface InlineImagePart {
    /** Content-ID value WITHOUT angle brackets (use `<${contentId}>` in the header). */
    contentId: string;
    mime: string;
    base64: string;
}

/** Pull base64 `data:` images out of the HTML, replacing each src with a
 *  `cid:` reference. Identical data: URIs (the same image pasted twice)
 *  collapse to one part. `idDomain` scopes the Content-IDs (RFC 2392 wants
 *  msg-id-like uniqueness). */
export function extractInlineImages(html: string, idDomain: string): { html: string; images: InlineImagePart[] } {
    const images: InlineImagePart[] = [];
    const byDataUri = new Map<string, string>();   // data-uri → contentId
    const stamp = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
    const out = html.replace(
        /(<img\b[^>]*?\ssrc=)(["'])(data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=\s]+))\2/gi,
        (_m, prefix: string, quote: string, dataUri: string, mime: string, b64: string) => {
            let cid = byDataUri.get(dataUri);
            if (!cid) {
                cid = `img${images.length + 1}.${stamp}@${idDomain}`;
                byDataUri.set(dataUri, cid);
                // Strip whitespace the editor may have wrapped into the URI;
                // the send path re-wraps at 76 cols per RFC 2045.
                images.push({ contentId: cid, mime, base64: b64.replace(/\s+/g, "") });
            }
            return `${prefix}${quote}cid:${cid}${quote}`;
        },
    );
    return { html: out, images };
}
