const dotenv = require("dotenv");
const axios = require("axios");
const { otpSenderTemplate } = require("./sms-no-templates/sms-no-templates");
const MessagesLogs = require("../models/MessagesLogs");
const Customers = require("../models/Customers");

dotenv.config();
const WHISPIR_URL = `https://api.ap1.whispir.com`;
const BUILDHUB_API_WORKSPACE = "21EDCB79B1B7F884";
const WHISPIR_HEADERS_CONTENT_TYPE_ACCEPT = `application/vnd.whispir.message-v1+json`;
const WHISPIR_RESOURCE_HEADERS_CONTENT_TYPE_ACCEPT = `application/vnd.whispir.resource-v1+json`;
const WHISPIR_BULKMESSAGING_CONTENT_TYPE_ACCEPT = `application/vnd.whispir.bulkmessage-v1+json`;
const WHISPIR_USERNAME = process.env.WHISPIR_USERNAME;
const WHISPIR_PASSWORD = process.env.WHISPIR_PASSWORD;
const WHISPIR_API_KEY = process.env.WHISPIR_API_KEY;

const whispirService = {
  messaging: {
    async singleMessage(dataObj, messageType) {
      const { recipientNumber, senderAlias = "Buildhub Ph SMS" } = dataObj;
      let msgTemplate = "",
        msgSubj = "";
      let requestBody;
      switch (messageType) {
        case "otp-sender":
          const { otp, otp_reference_no } = dataObj;

          msgTemplate = otpSenderTemplate(otp, otp_reference_no);
          msgSubj = "OTP";
          break;
        case "custom":
          const { customTemplate } = dataObj;
          msgTemplate = customTemplate;
          msgSubj = "Custom";
          break;
      }
      requestBody = {
        to: recipientNumber,
        subject: msgSubj,
        body: msgTemplate,
      };
      const response = await callMessageApi(
        `${WHISPIR_URL}/workspaces/${BUILDHUB_API_WORKSPACE}/messages`,
        senderAlias,
        requestBody
      );

      let customerId = 0;
      const customerDetail = await Customers.findOne({
        where: {
          phone: recipientNumber,
        },
      });

      if (customerDetail) customerId = customerDetail.id;
      const logs = await MessagesLogs.create({
        customer_id: customerId,
        type: "Message",
        receiver: recipientNumber,
        content: msgTemplate,
        is_sent: response ? true : false,
      });

      return response;
    },
    async multipleMessage(dataObj, messageType) {},
    async bulkMessaging(dataObj, messageTemplateId, senderAlias = "BuildCredit SMS") {
      const requestBody = {
        messageTemplateId,
        resource: {
          resourceId: dataObj.resourceId,
          smsMappingField: dataObj.mobile_mapping_field,
          options: {
            resolveRecipients: "true",
          },
        },
        callbackParameters: {
          CustomID: "12345",
        },
        callbackId: null,
      };

      const response = await callMessageApi(
        `${WHISPIR_URL}/workspaces/${BUILDHUB_API_WORKSPACE}/messages`,
        senderAlias,
        requestBody,
        true,
        false,
        true
      );

      return response;
    },
  },
  resource: {
    async createResource(jsonResource) {
      const stringifyJson = JSON.stringify(jsonResource);
      const resourceBody = {
        name: "resource-customers.csv",
        scope: "private",
        mimeType: "application/json",
        derefUri: Buffer.from(stringifyJson).toString("base64"),
      };

      const response = await callMessageApi(`${WHISPIR_URL}/resources`, "", resourceBody, true, true);
      return response;
    },
  },
};

const callMessageApi = async (
  requestUrl,
  senderAlias,
  requestBody,
  isTemplate = false,
  isResource = false,
  isBulkMessaging = false
) => {
  const isDevMode = process.env.DEVELOPMENT == "true";

  const credentials = Buffer.from(`${WHISPIR_USERNAME}:${WHISPIR_PASSWORD}`).toString("base64");
  const aliasOption = {
    aliasOption: {
      aliasName: senderAlias,
    },
  };

  const axiosHeaders = {
    headers: {
      Authorization: `Basic ${credentials}`,
      "Content-Type": isResource
        ? WHISPIR_RESOURCE_HEADERS_CONTENT_TYPE_ACCEPT
        : isBulkMessaging
        ? WHISPIR_BULKMESSAGING_CONTENT_TYPE_ACCEPT
        : WHISPIR_HEADERS_CONTENT_TYPE_ACCEPT,
      Accept: isResource
        ? WHISPIR_RESOURCE_HEADERS_CONTENT_TYPE_ACCEPT
        : isBulkMessaging
        ? WHISPIR_BULKMESSAGING_CONTENT_TYPE_ACCEPT
        : WHISPIR_HEADERS_CONTENT_TYPE_ACCEPT,
      "x-api-key": WHISPIR_API_KEY,
    },
  };

  isTemplate ? "" : (requestBody.features = aliasOption);

  try {
    if (!isDevMode) {
      const response = await axios.post(requestUrl, JSON.stringify(requestBody), axiosHeaders);
      return response;
    }
  } catch (err) {
    console.error(err);
  }
};

module.exports = whispirService;
