const { getUsefulLinks } = require("../utils/getQuery");
const { postEmailSub, postContactMessage } = require("../utils/postQuery");
const {
  sendSubConfirmation,
  sendContactMessage,
} = require("../utils/sendMail");

const router = require("express").Router();

// Get contact us form data
router.post("/formdata", async (req, res) => {
  let formData = req.body;
  try {
    const response = await postContactMessage(formData);
    if (response) {
      try {
        const info = await sendContactMessage(formData);
        if (info) {
          res.status(200).json("Data created successfully & Email sent.");
        }
      } catch (error) {
        res.status(500).json(error);
      }
    }
  } catch (error) {
    res.status(500).json(error);
  }
});

// Get subscriber email
router.post("/subscribe", async (req, res) => {
  let email = req.body;

  try {
    const response = await postEmailSub(email.email);
    if (response === "exist") {
      res.status(501).json("Email Exists!! :))");
    } else {
      try {
        await sendSubConfirmation(email.email);
        res.status(200).json(response);
      } catch (error) {
        console.log(error);
      }
    }
  } catch (error) {
    res.status(500).json(error);
  }
});

// Get Useful Links
router.get("/useful-links", async (req, res) => {
  try {
    const data = await getUsefulLinks();
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json(error);
  }
});

module.exports = router;
