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


export const sendWhatsappMC = async (
  mobile: string,
  formBody : any,
  file:any = null,
  templateName: string,
  projectId: string,
  credentials: any,
  clientId: number = 0,
) => {
  const F = "sendWhatsappMC";
  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);
    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`
        };
    }
    const messageBody = new FormData();
    messageBody.append("template_id", templateName);
    messageBody.append("country_code", "91");
    messageBody.append("phone_number", mobile);
    
    formBody.forEach((value: any, index: number) => {
      messageBody.append(`body_${index + 1}`, value);
    });
    if (file) {
      const fileName = path.basename(new URL(file).pathname) || "document.pdf";

      const response = await axios.get(file, {
        responseType: "arraybuffer",
      });
      
      
      //const fileName = path.basename(file);
      const buffer = Buffer.from(response.data);

      whatsappLog.info (
        `[${F}], Mobile [${mobile}], File Name [${fileName}],`
      );
      const fileObj = new File(
         [new Blob([buffer], { type: "application/pdf" })],
        fileName,
        {
          type: "application/pdf",
        }
      );
      messageBody.append("header_document", fileObj);
      whatsappLog.info (
        `[${F}], Mobile [${mobile}], File Name [${fileName}], Message sent successfully`
      );
    }
    
    const response2: any = await axios.post(
      `${process.env.WHATSAPP_MC_SEND_MESSAGE_URI}`,
      messageBody,
      {
        timeout: 8000,
        headers: {
          "X-Project-Id": projectId,
          "x-api-key": credentials?.key,
        },
      }
    );
  
    if (response2?.data?.response === 'SUCCESS') {
      whatsappLog.info (
        `[${F}], Mobile [${mobile}], Message sent successfully, Response : ${JSON.stringify(
          response2?.data
        )}`
      );
      return {
        status: true,
        message: `Message sent successfully`
      };
    } else {
      whatsappLog.info (
        `[${F}], Mobile [${mobile}], Unable to send message, Response : ${JSON.stringify(
          response2?.data
        )}`
      );
      return {
        status:false,
        message: `Error while sending message`
      };
    }
  } catch (error: any) {
    whatsappLog.info (
      `[${F}], Mobile [${mobile}], Error: ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );
    return {
        status: false,
        message: `Error while sending message`
    };
  }
};

export default sendWhatsappMC;
