import { realpathSync, statSync } from "node:fs";
import { basename } from "node:path";
// Matches the documented inbound email-attachment cap (PLUGIN.md) so inbound and
// outbound use one number, and over-cap fails loudly here instead of as an
// opaque SMTP rejection downstream.
export const OUTBOUND_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
/**
 * Validate agent-supplied attachment paths and map them to nodemailer's
 * { filename, path } shape. Mirrors the WhatsApp send-document account-scope
 * check: each path must realpath to a regular file under the account directory
 * and be within the size cap. Any violation throws a precise error naming the
 * offending path, so the caller sends no mail rather than a reply that silently
 * omits the file. Absent/empty input returns [] (a text-only message).
 */
export function resolveOutboundAttachments(accountDir, paths) {
    if (!paths || paths.length === 0)
        return [];
    if (!accountDir) {
        throw new Error("Cannot attach files: ACCOUNT_DIR is not set (no account context to validate paths against).");
    }
    let accountResolved;
    try {
        accountResolved = realpathSync(accountDir);
    }
    catch (err) {
        throw new Error(`Cannot attach files: account directory ${accountDir} is not accessible (${err instanceof Error ? err.message : String(err)}).`);
    }
    const out = [];
    for (const p of paths) {
        let resolvedPath;
        try {
            resolvedPath = realpathSync(p);
        }
        catch (err) {
            if (err.code === "ENOENT") {
                throw new Error(`Attachment not found: ${p}`);
            }
            throw new Error(`Cannot read attachment ${p}: ${err instanceof Error ? err.message : String(err)}`);
        }
        if (!resolvedPath.startsWith(accountResolved + "/")) {
            throw new Error(`Attachment ${p} is outside the account directory and cannot be sent.`);
        }
        const st = statSync(resolvedPath);
        if (!st.isFile()) {
            throw new Error(`Attachment ${p} is not a regular file.`);
        }
        if (st.size > OUTBOUND_ATTACHMENT_MAX_BYTES) {
            throw new Error(`Attachment ${basename(resolvedPath)} exceeds the 25 MB email limit (${(st.size / 1024 / 1024).toFixed(1)} MB).`);
        }
        out.push({ filename: basename(resolvedPath), path: resolvedPath });
    }
    return out;
}
/** The " with N attachment(s): a, b" suffix appended to an email-send/-reply
 *  success message. Empty string when nothing was attached. Lives here so both
 *  sender tools render the attachment list identically. */
export function formatAttachNote(attachments) {
    if (attachments.length === 0)
        return "";
    return ` with ${attachments.length} attachment(s): ${attachments
        .map((a) => a.filename)
        .join(", ")}`;
}
//# sourceMappingURL=attachment-resolve.js.map