const express = require("express");
const cors = require("cors");
const router = express.Router();
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

router.post("/send", (req, res, next) => {
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;
  var email = req.body.email;
  var message = req.body.message;

  var mail = {
    to: "snackabilityapp@gmail.com",
    from: "snackabilityapp@gmail.com",
    templateId: 'd-599c4604d6d94b68a271ff0060314f15',
  dynamicTemplateData: {
    userName: firstName + " " + lastName,
    userEmail: email,
    userMessage: message,
  },
  };

  var confirmation = {
    to: email,
    from: "snackabilityapp@gmail.com",
    templateId: 'd-85ea80a3b5644d399cb1ae1337eef432',
  dynamicTemplateData: {
    userName: firstName,
  },
  };

  sgMail
    .send(mail)
    .then(() => {
      console.log("Email sent");
      res.json({
        status: "success",
      });
    })
    .catch((error) => {
      console.error(error);
      res.json({
        status: "fail",
      });
    });

    sgMail
    .send(confirmation)
    .then(() => {
      console.log("Confirmation email sent");
    })
    .catch((error) => {
      console.error(error);
    });
});

module.exports = router;
