import { getIO } from "../libs/socket";
import Contact from "../models/Contact";
import Ticket from "../models/Ticket";
import {
  isValidMsg,
  verifyMessage
} from "../services/WbotServices/wbotMessageListener";

import whatsappOfficialAPI from "./WhatsappOfficialAPI";

async function sendWhatsAppMessageOfficialAPI(
  ticket: Ticket,
  body: string,
  quotedMsgSerializedId?: any | undefined,
  _template?: any
) {
  const { contactId, phoneNumberId } = ticket;

  const contact: any = await Contact.findByPk(contactId);

  const { number } = contact;

  let data: any = {
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: number
  };

  if (_template) {
    const { template } = _template;
    data = {
      ...data,
      type: "template",
      template
    };
  } else {
    data = {
      ...data,
      type: "text",
      text: {
        preview_url: true,
        body
      }
    };
  }

  if (quotedMsgSerializedId) {
    data = { ...data, context: { message_id: quotedMsgSerializedId.id } };
  }

  if (!isValidMsg({ type: data.type })) {
    return;
  }

  console.log("SEND MESSAGE: ", JSON.stringify(data, null,2));
 
  whatsappOfficialAPI
    .post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data)
    .then(response => {
      console.log("Response:", response.data);

      let msg = {};

      msg = {
        ...msg,
        id: { id: response.data.messages[0].id },
        fromMe: true,
        type: "chat",
        read: false,
        phoneNumberId,
        body
      };

      verifyMessage(msg, ticket, contact, quotedMsgSerializedId?.id);
    })
    .catch(error => {
      console.log("Error on try request: ", error.response.data.error.message);
    });
}

export default sendWhatsAppMessageOfficialAPI;
