// 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 async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
    console.log(req.body)

    const {
        firstName,
        lastName,
        subject,
        email,
        summary,
        captchaToken

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

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

    console.log(JSON.stringify({SMTP_PROXY_EMAIL, SMTP_RECIPIENT_EMAIL, SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD}));
    
    try {
        
        const response = await fetch(
            `https://www.google.com/recaptcha/api/siteverify?secret=${RECAPTCHA_SECRET_KEY}&response=${captchaToken}`
        );
        if ((await response.json()).success) {
            //reCaptcha verification successfull
            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);
                    // res.status(500).send('Internal Server Error');
                    res.status(500).end();

                }
                else {
                    console.log('successful');
                    console.log(info);
                    res.status(200).end();
                }
              })
            
            res.status(200).json(req.body);
        } else {
            // reCAPTCHA verification failed
            // res.status(400).send('reCAPTCHA verification failed.');
            res.status(400).end();
        }
    } catch (error) {
        console.error(error);
        // res.status(500).send('Internal server error');
        res.status(500).end();
    }
    

}
