import { createTransport } from "nodemailer";
const CONNECT_TIMEOUT = 10_000;
/**
 * Create an SMTP transporter from the email config.
 */
function createSmtpTransport(config, password) {
    return createTransport({
        host: config.smtpHost,
        port: config.smtpPort,
        secure: config.smtpSecurity === "tls",
        auth: {
            user: config.email,
            pass: password,
        },
        tls: {
            rejectUnauthorized: true,
        },
        connectionTimeout: CONNECT_TIMEOUT,
        greetingTimeout: CONNECT_TIMEOUT,
    });
}
/**
 * Test SMTP connectivity and authentication.
 * Returns null on success, error message on failure.
 */
export async function testConnection(config, password) {
    const transport = createSmtpTransport(config, password);
    try {
        await transport.verify();
        return null;
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        if (msg.includes("EAUTH") || msg.includes("Invalid login") || msg.includes("Authentication") || msg.includes("535")) {
            return `SMTP authentication failed for ${config.email}. Check the password — most providers require an app-specific password when 2FA is enabled.`;
        }
        if (msg.includes("ECONNREFUSED")) {
            return `SMTP connection refused at ${config.smtpHost}:${config.smtpPort}. Check the hostname and port.`;
        }
        if (msg.includes("ENOTFOUND")) {
            return `SMTP host ${config.smtpHost} not found. Check the hostname.`;
        }
        if (msg.includes("certificate") || msg.includes("TLS") || msg.includes("SSL")) {
            return `SMTP TLS error connecting to ${config.smtpHost}:${config.smtpPort}. Try port 587 (STARTTLS) or 465 (TLS).`;
        }
        if (msg.includes("ETIMEDOUT") || msg.includes("timeout")) {
            return `SMTP connection timed out to ${config.smtpHost}:${config.smtpPort}. Check the host and port.`;
        }
        return `SMTP connection failed: ${msg}`;
    }
    finally {
        transport.close();
    }
}
/**
 * Send an email via SMTP.
 */
export async function sendEmail(config, password, options) {
    const transport = createSmtpTransport(config, password);
    try {
        const info = await transport.sendMail({
            from: config.agentAddress,
            to: options.to,
            subject: options.subject,
            text: options.body,
            html: options.html,
            inReplyTo: options.inReplyTo,
            references: options.references,
            headers: options.headers,
            attachments: options.attachments,
        });
        return { messageId: info.messageId };
    }
    finally {
        transport.close();
    }
}
//# sourceMappingURL=smtp.js.map