import { Injectable } from "@nestjs/common";
import { AppConfigService } from "./app-config.service";
import { LoggerService } from "src/common/logger/logger.service";
const mg = require("nodemailer-mailgun-transport")
const nodemailer = require("nodemailer");

@Injectable()
export class MailService {
    constructor(
        private appConfigService: AppConfigService,
        private loggerService: LoggerService
    ) {}

    async sendMail({ to, subject, htmlContent }: any): Promise<void> {
        const transporter = nodemailer.createTransport(mg({
            auth: {
                domain: this.appConfigService.mail().domain,
                api_key: this.appConfigService.mail().api_key,
            }
        }));
        
        const sent = await transporter.sendMail({
            from: `"${this.appConfigService.mail().from_name}" <${this.appConfigService.mail().from_email}>`, // sender address
            to: to.map(item => `"${item.name}" <${item.email}>`).join(","), // list of receivers
            subject, // Subject line
            html: htmlContent, // html body
        });

        this.loggerService.log('info', JSON.stringify(sent))
    }
}
