import axios from "axios";
import fs from "fs";
import path from "path";
import { whatsappLog } from "../../serviceLog";
import CONSTANTS from "../../../config/constants";

const addUserToWhatsapp = async (
  mobile: string,
  tenantName: string,
  key: any,
) => {
  const F = "addUserToWhatsapp";
  try {
    let formattedMobile = mobile.trim().replace(" ", "");

    const body = {
      countryCode: "+91",
      userId: formattedMobile,
      phoneNumber: formattedMobile,
      traits: {
        name: tenantName,
        email: "",
      },
      tags: ["sample-tag-1", "sample-tag-2"],
    };

    const response: any = await axios.post(
      `${process.env.WHATSAPP_ADD_USER_URI}`,
      body,
      {
        timeout: 8000,
        headers: {
          "Content-Type": "application/json",
          Authorization: key,
        },
      },
    );
    if (response?.data?.result) {
      whatsappLog.info(
        `[${F}], Mobile [${mobile}], User Added successfully, Response : ${JSON.stringify(
          response?.data
        )}`
      );
      return true;
    } else {
      whatsappLog.info(
        `[${F}], Mobile [${mobile}], Unable to add user, Response : ${JSON.stringify(
          response?.data
        )}`
      );
      return false;
    }
  } catch (error: any) {
    whatsappLog.info(
      `[${F}], Mobile [${mobile}], Error: ${JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return false;
  }
};

export const sendWhatsappInterakt = async (
  mobile: string,
  name: string,
  formBody: any,
  userType: any,
  templateType: any,
  file: any = null,
  templateName: string,
  lang: string,
  credentials: any,
  clientId: number = 0,
  propId: number = 0,
) => {
  const F = "sendWhatsappInterakt";
  try {
    const validateMobile = (mobile: string) => {
      const number = mobile.replace(/\D/g, "").slice(-10);

      return /^[6-9]\d{9}$/.test(number) ? `${number}` : null;
    };
    let mobileNumber = validateMobile(mobile)?.toString();
    if (!mobileNumber) {
      whatsappLog.info(
        `[${F}], Client Id [${clientId}], Mobile [${mobileNumber}], Failed to send Not a valid mobile number`
      );
      return {
        status: false,
        message: `Not a valid number`
      };
    }
    /*Adding User To interakt*/
    let userAdded = await addUserToWhatsapp(mobileNumber, name, credentials?.key);
    if (!userAdded) {
      whatsappLog.info(
        `[${F}], Client Id [${clientId}], Mobile [${mobileNumber}], Failed to add user
        )}`
      );
      return {
        status: false,
        message: `Failed to add user`

      };
    }
    let template: any = {
      name: templateName,
      languageCode: lang,
      bodyValues: formBody
    }
    if (file) {
      template = {
        name: templateName,
        languageCode: lang,
        headerValues: [file],
        bodyValues: formBody
      }
    }

    if(userType === CONSTANTS.USER_TYPE.CLIENT && templateType === CONSTANTS.WHATSAPP_TEMPLATE_TYPES.CLIENT.OTP) {
     template = {
        name: templateName,
        languageCode: lang,
        bodyValues: formBody,
        buttonValues: {0:formBody},
      } 
    }
    const messageBody = {
      countryCode: "+91",
      userId: mobileNumber,
      phoneNumber: mobileNumber,
      callbackData: "some text here",
      type: "Template",
      template: template,
    };

    const response: any = await axios.post(
      `${process.env.WHATSAPP_SEND_MESSAGE_URI}`,
      messageBody,
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: credentials?.key,
        },
      }
    );

    if (response?.data?.result) {
      whatsappLog.info(
        `[${F}], Client Id [${clientId}], Mobile [${mobile}], Message sent successfully, Response : ${JSON.stringify(
          response?.data
        )}`
      );
      return {
        status: true,
        message: `Message sent successfully`

      };
    } else {
      whatsappLog.info(
        `[${F}], Client Id [${clientId}], Mobile [${mobile}], Unable to send message, Response : ${JSON.stringify(
          response?.data
        )}`
      );
      return {
        status: false,
        message: `Error while sending message`

      };
    }
  } catch (error: any) {
    whatsappLog.info(
      `[${F}], Client Id [${clientId}], Mobile [${mobile}], Error: ${JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return {
      status: false,
      message: `Error while sending message`

    };
  }
};

export default sendWhatsappInterakt;
