"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendOtpEmail = void 0;
const nodemailer_1 = __importDefault(require("nodemailer"));
const hasSmtpConfig = Boolean(process.env.SMTP_HOST && process.env.SMTP_PORT && process.env.SMTP_USER && process.env.SMTP_PASS);
const transporter = hasSmtpConfig
    ? nodemailer_1.default.createTransport({
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT),
        secure: process.env.SMTP_SECURE === "true",
        auth: {
            user: process.env.SMTP_USER,
            pass: process.env.SMTP_PASS,
        },
        tls: {
            rejectUnauthorized: false,
        },
        connectionTimeout: 10000,
        greetingTimeout: 10000,
        socketTimeout: 15000,
    })
    : null;
const logOtpToConsole = (to, code, purpose, expiresInMinutes) => {
    const label = purpose === "Staff verification" ? "OTP for admin" : purpose;
    console.log("=".repeat(50));
    console.log(`[DEV OTP] ${label}`);
    console.log(`  Email: ${to}`);
    console.log(`  Code:  ${code}`);
    console.log(`  Expires in: ${expiresInMinutes} minutes`);
    console.log("=".repeat(50));
};
const sendOtpEmail = async ({ to, code, purpose, expiresInMinutes }) => {
    const subject = `${purpose} OTP`;
    const text = `Your OTP code is ${code}. It expires in ${expiresInMinutes} minutes. If you did not request this, ignore this email.`;
    logOtpToConsole(to, code, purpose, expiresInMinutes);
    if (!transporter) {
        return "console";
    }
    try {
        await transporter.sendMail({
            from: process.env.SMTP_FROM || process.env.SMTP_USER,
            to,
            subject,
            text,
        });
        console.log(`[EMAIL] OTP sent to ${to}`);
        return "email";
    }
    catch (err) {
        console.warn(`[EMAIL] Failed to send OTP to ${to}:`, err instanceof Error ? err.message : err);
        return "console";
    }
};
exports.sendOtpEmail = sendOtpEmail;
//# sourceMappingURL=mailer.js.map