"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var SMTPEMailService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SMTPEMailService = void 0;
const common_1 = require("@nestjs/common");
const handlebars_1 = __importDefault(require("handlebars"));
const mail_provider_decorator_1 = require("../../decorators/mail-provider.decorator");
const email_template_service_1 = require("../email-template.service");
const publisher_factory_service_1 = require("../queues/publisher-factory.service");
const setting_service_1 = require("../setting.service");
const nodemailer = require("nodemailer");
let SMTPEMailService = SMTPEMailService_1 = class SMTPEMailService {
    constructor(publisherFactory, emailTemplateService, settingService) {
        this.publisherFactory = publisherFactory;
        this.emailTemplateService = emailTemplateService;
        this.settingService = settingService;
        this.logger = new common_1.Logger(SMTPEMailService_1.name);
        const host = process.env.COMMON_SMTP_EMAIL_SMTP_HOST;
        const port = +(process.env.COMMON_SMTP_EMAIL_SMTP_PORT ?? 587);
        const username = process.env.COMMON_SMTP_EMAIL_USERNAME;
        const password = process.env.COMMON_SMTP_EMAIL_PASSWORD;
        const from = process.env.COMMON_SMTP_EMAIL_FROM ?? process.env.COMMON_EMAIL_FROM;
        this.transporter = nodemailer.createTransport({
            host: host,
            port: port,
            secure: port === 465,
            auth: {
                user: username,
                pass: password
            }
        });
    }
    async sendEmailUsingTemplate(to, templateName, templateParams, shouldQueueEmails = false, wrapperAttachments, attachments, parentEntity, parentEntityId, cc, bcc, from) {
        const emailTemplate = await this.emailTemplateService.findOneByName(templateName);
        if (!emailTemplate) {
            throw new Error(`Invalid template name ${templateName}`);
        }
        const bodyTemplate = handlebars_1.default.compile(emailTemplate.body);
        const body = bodyTemplate(templateParams);
        const subjectTemplate = handlebars_1.default.compile(emailTemplate.subject);
        const subject = subjectTemplate(templateParams);
        return await this.sendEmail(to, subject, body, shouldQueueEmails, wrapperAttachments, attachments, parentEntity, parentEntityId, cc, bcc, from);
    }
    async sendEmail(to, subject, body, shouldQueueEmails = false, wrapperAttachments, attachments, parentEntity, parentEntityId, cc, bcc, from) {
        const message = {
            payload: {
                from: from || this.settingService.getConfigValue("smtpMailFrom"),
                to: to,
                subject: subject,
                body: body,
                attachments: attachments,
                cc: cc,
                bcc: bcc,
            },
            parentEntity: parentEntity,
            parentEntityId: parentEntityId,
        };
        if (shouldQueueEmails === true) {
            return this.sendEmailAsynchronously(message);
        }
        else if (shouldQueueEmails == false && this.settingService.getConfigValue("shouldQueueEmails") === true) {
            return this.sendEmailAsynchronously(message);
        }
        else {
            return await this.sendEmailSynchronously(message);
        }
    }
    async sendEmailAsynchronously(message) {
        const { to, subject, body } = message.payload;
        this.logger.debug(`Queueing email to ${to} with subject ${subject} and body ${body}`);
        return this.publisherFactory.publish(message, 'SmtpEmailQueuePublisher');
    }
    async sendEmailSynchronously(message) {
        let from;
        const { to, subject, body, attachments = [], cc, bcc } = message.payload;
        const envFrom = this.settingService.getConfigValue("smtpMailFrom");
        if (envFrom) {
            from = envFrom;
        }
        if (!from || !to || !subject || !body) {
            this.logger.error(`Required fields are missing in the email message: ${JSON.stringify(message.payload)}`);
            return;
        }
        const attachmentsList = attachments?.map((attachment) => {
            const attachmentEntry = {
                filename: attachment.filename,
                contentType: attachment.contentType,
            };
            if (attachment.path) {
                attachmentEntry['path'] = attachment.path;
            }
            if (attachment.content) {
                attachmentEntry['content'] = attachment.content;
            }
            return attachmentEntry;
        }) || [];
        const r = await this.transporter.sendMail({
            from: from,
            to: to,
            cc: cc,
            bcc: bcc,
            subject: subject,
            html: body,
            attachments: attachmentsList,
        });
        return r;
    }
};
exports.SMTPEMailService = SMTPEMailService;
exports.SMTPEMailService = SMTPEMailService = SMTPEMailService_1 = __decorate([
    (0, common_1.Injectable)(),
    (0, mail_provider_decorator_1.MailProvider)(),
    __metadata("design:paramtypes", [publisher_factory_service_1.PublisherFactory,
        email_template_service_1.EmailTemplateService,
        setting_service_1.SettingService])
], SMTPEMailService);
//# sourceMappingURL=smtp-email.service.js.map