const fetch = require('node-fetch-commonjs')
const fs = require('fs');
const path = require('path');

exports.handler = async function (event) {
    if (event.body === null) {
      return {
        statusCode: 400,
        body: JSON.stringify("Payload required"),
      };
    }
  
    const requestBody = JSON.parse(event.body)

    const file = fs.readFileSync(path.resolve("./netlify/functions/triggerLearnMoreEmail/assets/Whitepaper.pdf")).toString("base64");

    //automatically generated snippet from the email preview
    //sends a request to an email handler for a subscribed email
    await fetch(`${process.env.URL}/.netlify/functions/emails/WhitePaper`, {
        headers: {
          "netlify-emails-secret": process.env.NEXT_PUBLIC_NETLIFY_EMAILS_SECRET,
        },
        method: "POST",
        body: JSON.stringify({
            from: process.env.NEXT_PUBLIC_NETLIFY_FROM_EMAIL,
            to: requestBody.subscriberEmail,
            subject: "Thanks For Visiting Sign365",
            attachments: [{
                content: file,
                filename: "Whitepaper.pdf",
                type: "pdf",
            }],
            parameters: {
                email: requestBody.subscriberEmail,
            },
        }),
      }
    );
  
    return {
      statusCode: 200,
      body: JSON.stringify("WhitePaper email sent!"),
    };
}