import * as nodemailer from "nodemailer";
import yenv from "yenv";
import { MailInterface } from "../utills/common";
const env = yenv("env.yaml", { env: "development" });
export default class MailService {
  private static instance: MailService;
  private transporter!: nodemailer.Transporter;

  private constructor() {
    // Initialize transporter when MailService is instantiated
    this.createLocalConnection();
  }

  static getInstance() {
    if (!MailService.instance) {
      MailService.instance = new MailService();
    }

    return MailService.instance;
  }

  async createLocalConnection() {
    this.transporter = nodemailer.createTransport({
      host: env.SMTP_HOST,
      port: env.SMTP_PORT,
      secure: false,
      auth: {
        user: env.SMTP_USERNAME,
        pass: env.SMTP_PASSWORD,
      },
    });
  }

  async sendMail(requestId: string | number, options: MailInterface) {
    // Ensure transporter is initialized before sending mail
    if (!this.transporter) {
      throw new Error("Transporter not initialized. Call createLocalConnection() first.");
    }

    return this.transporter.sendMail({
      from: options.from,
      to: options.to,
      subject: options.subject,
      text: options.text,
      html: options.html,
    }).then((info) => {
      return info;
    });
  }
  async verifyConnection() {
    if (!this.transporter) {
      throw new Error("Transporter not initialized. Call createLocalConnection() first.");
    }

    return this.transporter.verify();
  }
  getTransporter() {
    return this.transporter;
  }
}
