import assert from 'assert';
import nodemailer, { type SendMailOptions } from 'nodemailer';
import config from '@/shared/config';

interface EmailMessage {
  to: string;
  subject: string;
  html: () => Promise<string>;
}

class EmailSender {
  email: EmailMessage;

  constructor(email: EmailMessage) {
    this.email = email;
  }

  async send() {
    assert(this.email, 'email is required');
    assert(this.email.to, 'email.to is required');
    assert(this.email.subject, 'email.subject is required');
    assert(this.email.html, 'email.html is required');

    const htmlContent = await this.email.html();

    const transporter = nodemailer.createTransport(this.transportConfig);

    const mailOptions: SendMailOptions = {
      from: this.from,
      to: this.email.to,
      subject: this.email.subject,
      html: htmlContent,
      headers: {
        'X-SES-CONFIGURATION-SET': 'flatlogic-app',
      },
    };

    return transporter.sendMail(mailOptions);
  }

  static get isConfigured(): boolean {
    return Boolean(config.email?.auth?.pass) && Boolean(config.email?.auth?.user);
  }

  get transportConfig() {
    return config.email;
  }

  get from() {
    return config.email.from;
  }
}

export default EmailSender;
