const path = require("path");
require("dotenv").config({
  path: path.resolve(
    process.cwd(),
    `.env.${process.env.NODE_ENV || "development"}`
  ),
});

const twilio = require("twilio");
const { phone } = require("phone");
const queries = require("../graphql-client/queries");
const logger = require("../utils/logger");
const client = twilio(
  process.env.TWILIO_AUTH_TOKEN,
  process.env.TWILIO_AUTH_KEY
);
const { admin } = require("../firebase/firebase-handler");

const gqlClient = require("../graphql-client/graphql-client").client;

exports.send = (req, res) => {
  const {
    to,
    messagingServiceSid,
    body,
    conversationid,
    selectedMedia,
    imexshopid,
  } = req.body;

  logger.log("sms-outbound", "DEBUG", req.user.email, null, {
    messagingServiceSid: messagingServiceSid,
    to: phone(to).phoneNumber,
    mediaUrl: selectedMedia.map((i) => i.src),
    text: body,
    conversationid,
    isoutbound: true,
    userid: req.user.email,
    image: req.body.selectedMedia.length > 0,
    image_path:
      req.body.selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : [],
  });

  if (
    !!to &&
    !!messagingServiceSid &&
    (!!body || !!selectedMedia.length > 0) &&
    !!conversationid
  ) {
    client.messages
      .create({
        body: body,
        messagingServiceSid: messagingServiceSid,
        to: phone(to).phoneNumber,
        mediaUrl: selectedMedia.map((i) => i.src),
      })
      .then((message) => {
        let newMessage = {
          msid: message.sid,
          text: body,
          conversationid,
          isoutbound: true,
          userid: req.user.email,
          image: req.body.selectedMedia.length > 0,
          image_path:
            req.body.selectedMedia.length > 0
              ? selectedMedia.map((i) => i.src)
              : [],
        };
        gqlClient
          .request(queries.INSERT_MESSAGE, { msg: newMessage, conversationid })
          .then((r2) => {
            //console.log("Responding GQL Message ID", JSON.stringify(r2));
            logger.log("sms-outbound-success", "DEBUG", req.user.email, null, {
              msid: message.sid,
              conversationid,
            });

            const data = {
              type: "messaging-outbound",
              conversationid: newMessage.conversationid || "",
            };

            admin.messaging().send({
              topic: `${imexshopid}-messaging`,
              data,
            });

            res.sendStatus(200);
          })
          .catch((e2) => {
            logger.log("sms-outbound-error", "ERROR", req.user.email, null, {
              msid: message.sid,
              conversationid,
              error: e2,
            });

            //res.json({ success: false, message: e2 });
          });
      })
      .catch((e1) => {
        //res.json({ success: false, message: error });
        logger.log("sms-outbound-error", "ERROR", req.user.email, null, {
          conversationid,
          error: e1,
        });
      });
  } else {
    logger.log("sms-outbound-error", "ERROR", req.user.email, null, {
      type: "missing-parameters",
      messagingServiceSid: messagingServiceSid,
      to: phone(to).phoneNumber,
      text: body,
      conversationid,
      isoutbound: true,
      userid: req.user.email,
      image: req.body.selectedMedia.length > 0,
      image_path:
        req.body.selectedMedia.length > 0
          ? selectedMedia.map((i) => i.src)
          : [],
    });
    res
      .status(400)
      .json({ success: false, message: "Missing required parameter(s)." });
  }
};
