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

const client = require("../graphql-client/graphql-client").client;
const queries = require("../graphql-client/queries");
const { phone } = require("phone");
const { admin } = require("../firebase/firebase-handler");
const logger = require("../utils/logger");
exports.receive = async (req, res) => {
  //Perform request validation

  logger.log("sms-inbound", "DEBUG", "api", null, {
    msid: req.body.SmsMessageSid,
    text: req.body.Body,
    image: !!req.body.MediaUrl0,
    image_path: generateMediaArray(req.body),
  });

  if (
    !!!req.body ||
    !!!req.body.MessagingServiceSid ||
    !!!req.body.SmsMessageSid
  ) {
    logger.log("sms-inbound-error", "ERROR", "api", null, {
      msid: req.body.SmsMessageSid,
      text: req.body.Body,
      image: !!req.body.MediaUrl0,
      image_path: generateMediaArray(req.body),
      type: "malformed-request",
    });
    res.status(400);
    res.json({ success: false, error: "Malformed Request" });
  } else {
    try {
      const response = await client.request(
        queries.FIND_BODYSHOP_BY_MESSAGING_SERVICE_SID,
        {
          mssid: req.body.MessagingServiceSid,
          phone: phone(req.body.From).phoneNumber,
        }
      );

      let newMessage = {
        msid: req.body.SmsMessageSid,
        text: req.body.Body,
        image: !!req.body.MediaUrl0,
        image_path: generateMediaArray(req.body),
      };
      if (response.bodyshops[0]) {
        //Found a bodyshop - should always happen.
        if (response.bodyshops[0].conversations.length === 0) {
          //No conversation Found, create one.
          console.log("[SMS Receive] No conversation found. Creating one.");
          newMessage.conversation = {
            data: {
              bodyshopid: response.bodyshops[0].id,
              phone_num: phone(req.body.From).phoneNumber,
            },
          };
        } else if (response.bodyshops[0].conversations.length === 1) {
          //Just add it to the conversation
          console.log("[SMS Receive] Conversation found. Added ID.");
          newMessage.conversationid = response.bodyshops[0].conversations[0].id;
        } else {
          //We should never get here.
          logger.log("sms-inbound-error", "ERROR", "api", null, {
            msid: req.body.SmsMessageSid,
            text: req.body.Body,
            image: !!req.body.MediaUrl0,
            image_path: generateMediaArray(req.body),
            messagingServiceSid: req.body.MessagingServiceSid,
            type: "duplicate-phone",
          });
        }
        try {
          let insertresp;
          if (response.bodyshops[0].conversations[0]) {
            insertresp = await client.request(queries.INSERT_MESSAGE, {
              msg: newMessage,
              conversationid:
                response.bodyshops[0].conversations[0] &&
                response.bodyshops[0].conversations[0].id,
            });
          } else {
            insertresp = await client.request(queries.RECEIVE_MESSAGE, {
              msg: newMessage,
            });
          }
          const message = insertresp.insert_messages.returning[0];
          const data = {
            type: "messaging-inbound",
            conversationid: message.conversationid || "",
            text: message.text || "",
            messageid: message.id || "",
            phone_num: message.conversation.phone_num || "",
          };

          const fcmresp = await admin.messaging().send({
            topic: `${message.conversation.bodyshop.imexshopid}-messaging`,
            notification: {
              title: `ImEX Online Message - ${data.phone_num}`,
              body: message.image_path ? `Image ${message.text}` : message.text,
              //imageUrl: "https://thinkimex.com/img/io-fcm.png",
            },
            data,
          });

          logger.log("sms-inbound-success", "DEBUG", "api", null, {
            newMessage,
            fcmresp,
          });
          res.status(200).send("");
        } catch (e2) {
          logger.log("sms-inbound-error", "ERROR", "api", null, {
            msid: req.body.SmsMessageSid,
            text: req.body.Body,
            image: !!req.body.MediaUrl0,
            image_path: generateMediaArray(req.body),
            messagingServiceSid: req.body.MessagingServiceSid,
            error: e2,
          });

          res.sendStatus(500).json(e2);
        }
      }
    } catch (e1) {
      console.log("e1", e1);
      res.sendStatus(500).json(e1);
    }
  }
};

//    const sampleMessage: {
//   "ToCountry": "CA",
//   "ToState": "BC",
//   "SmsMessageSid": "SMad7bddaf3454c0904999d6018b1e8f49",
//   "NumMedia": "0",
//   "ToCity": "Vancouver",
//   "FromZip": "",
//   "SmsSid": "SMad7bddaf3454c0904999d6018b1e8f49",
//   "FromState": "BC",
//   "SmsStatus": "received",
//   "FromCity": "VANCOUVER",
//   "Body": "Hi",
//   "FromCountry": "CA",
//   "To": "+16043301606",
//   "MessagingServiceSid": "MG6e259e2add04ffa0d0aa355038670ee1",
//   "ToZip": "",
//   "NumSegments": "1",
//   "MessageSid": "SMad7bddaf3454c0904999d6018b1e8f49",
//   "AccountSid": "AC6c09d337d6b9c68ab6488c2052bd457c",
//   "From": "+16049992002",
//   "ApiVersion": "2010-04-01"
// }
// ] req.body {
//   [0]   ToCountry: 'CA',
//   [0]   MediaContentType0: 'image/jpeg',
//   [0]   ToState: 'BC',
//   [0]   SmsMessageSid: 'MM14fa2851ba26e0dc2b62073f8e7cdf27',
//   [0]   NumMedia: '1',
//   [0]   ToCity: 'Vancouver',
//   [0]   FromZip: '',
//   [0]   SmsSid: 'MM14fa2851ba26e0dc2b62073f8e7cdf27',
//   [0]   FromState: 'BC',
//   [0]   SmsStatus: 'received',
//   [0]   FromCity: 'VANCOUVER',
//   [0]   Body: '',
//   [0]   FromCountry: 'CA',
//   [0]   To: '+16043301606',
//   [0]   MessagingServiceSid: 'MG6e259e2add04ffa0d0aa355038670ee1',
//   [0]   ToZip: '',
//   [0]   NumSegments: '1',
//   [0]   MessageSid: 'MM14fa2851ba26e0dc2b62073f8e7cdf27',
//   [0]   AccountSid: 'AC6c09d337d6b9c68ab6488c2052bd457c',
//   [0]   From: '+16049992002',
//   [0]   MediaUrl0: 'https://api.twilio.com/2010-04-01/Accounts/AC6c09d337d6b9c68ab6488c2052bd457c/Messages/MM14fa2851ba26e0dc2b62073f8e7cdf27/Media/MEf129dd37979852f395eb29ffb126e19e',
//   [0]   ApiVersion: '2010-04-01'
//   [0] }

// [0]   MediaContentType0: 'image/jpeg',
// MediaContentType0: 'video/3gpp',

const generateMediaArray = (body) => {
  const { NumMedia } = body;
  if (parseInt(NumMedia) > 0) {
    //stuff
    const ret = [];
    for (var i = 0; i < parseInt(NumMedia); i++) {
      ret.push(body[`MediaUrl${i}`]);
    }
    return ret;
  } else {
    return null;
  }
};
