import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import nodemailer, { SentMessageInfo, Transporter } from 'nodemailer';
import { Options } from 'nodemailer/lib/smtp-connection';

import { ContactForm } from './contact-form.interface';
import { contactFormTemplate } from './templates/contact-form';

@Injectable()
export class EmailService {
  private readonly transporter: Transporter;

  constructor(private readonly $config: ConfigService) {
    this.transporter = nodemailer.createTransport({
      host: this.$config.get<string>('MAIL_HOST'),
      auth: {
        user: this.$config.get<string>('MAIL_USER'),
        password: this.$config.get<string>('MAIL_PASSWORD')
      },
      from: this.$config.get<string>('MAIL_FROM')
    } as Options);
  }

  public async sendContactForm(mail: ContactForm) {
    const mailContent = contactFormTemplate({
      name: mail.name,
      email: mail.email,
      subject: mail.subject,
      message: mail.message
    });

    this.transporter.sendMail({
      to: '',
      from: '"No Reply" <noreply@agineek.com>',
      subject: mail.subject,
      html: mailContent
    });
  }
}
