import * as nodemailer from 'nodemailer';
import * as handlebars from 'handlebars';
import * as fs from 'fs';
import { TransactionPaymentType } from 'src/modules/transaction/transaction/constants';
import { InvoiceType } from 'src/modules/configuration/export/constants';

export async function sendEmail(receivers, invoiceType, attachment?) {
  const smtpTransport = nodemailer.createTransport({
    host: process.env.EMAIL_HOST,
    port: process.env.EMAIL_POST,
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_TOKEN,
    },
  });

  for (const receiver of receivers) {
    try {
      const templateName = getTemplate(receiver.payment_type, invoiceType);
      const templatePath = `./assets/email-template/redesign/${templateName}.html`;
      const templateSource = fs.readFileSync(templatePath, 'utf8');

      const template = handlebars.compile(templateSource);
      const htmlToSend = template(receiver);

      const emailContext = {
        from: process.env.EMAIL_SENDER ?? 'no-reply@weplayground.app',
        to: receiver.email,
        subject: invoiceType,
        html: htmlToSend,
        attachDataUrls: true,
        attachments: [
          {
            filename: `${invoiceType}.pdf`,
            content: attachment,
          },
        ],
      };

      await new Promise((f) => setTimeout(f, 2000));

      smtpTransport.sendMail(emailContext, function (err) {
        if (err) {
          console.log(err, `Error occurs on send to ${receiver.email}`);
        } else {
          console.log(`Email sent to ${receiver.email}`);
        }
      });
    } catch (error) {
      console.log(error, `Error occurs on send to ${receiver.email}`);
    }
  }
}

function getTemplate(transactionType, invoiceType) {
  if (invoiceType == InvoiceType.BOOKING_DATE_CHANGE) {
    return 'change-date-information';
  } else if (invoiceType == InvoiceType.INVOICE_EXPIRED) {
    return 'invoice-expired';
  } else if (invoiceType == InvoiceType.REFUND_REQUEST) {
    return 'refund-request';
  } else if (invoiceType == InvoiceType.REFUND_CONFIRMATION) {
    return 'refund-confirmation';
  } else if (invoiceType == InvoiceType.PAYMENT_CONFIRMATION) {
    return 'payment-confirmation';
  } else if (
    invoiceType == InvoiceType.BOOKING_INVOICE &&
    transactionType != TransactionPaymentType.MIDTRANS
  ) {
    return 'invoice-bank';
  } else if (invoiceType == InvoiceType.BOOKING_INVOICE) {
    return 'invoice-midtrans';
  }
}
