// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import nodemailer from 'nodemailer';

type Data = {
  firstName: string,
  lastName: string,
  email: string,
  subject: string,
  summary: string,
}

type MailData = {
    from?: string,
    to?: string,
    subject?: string,
    text?: string,
    html?: string
  }

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
    console.log(req.body)

    const {
        firstName,
        lastName,
        subject,
        email,
        summary

    } = req.body;
    const {SMTP_PROXY_EMAIL, SMTP_RECIPIENT_EMAIL, SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD} = process.env;

    console.log(JSON.stringify({SMTP_PROXY_EMAIL, SMTP_RECIPIENT_EMAIL, SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD}));
    const transporter = nodemailer.createTransport({
        port: parseInt(SMTP_PORT!),
        host: SMTP_HOST!,
        auth: {
            user: SMTP_USERNAME!,
            pass: SMTP_PASSWORD!,
        },
        secure: true,
    });

    const mailData: MailData = {
        from: SMTP_PROXY_EMAIL!,
        to: SMTP_RECIPIENT_EMAIL!,
        subject: `Message From ${firstName} ${lastName}: ${subject}`,
        text: summary + " | Sent from: " + email,
        html: `<div>${summary}</div><p>Sent from:
        ${email}</p>`
      }

    transporter.sendMail(mailData, function (err, info) {
        if(err)
          console.log(err)
        else
          console.log(info)
      })
    
    res.status(200).json(req.body);
}
