import { Message as WbotMessage } from "whatsapp-web.js";
import Ticket from "../models/Ticket";
import GetTicketWbot from "./GetTicketWbot";
import AppError from "../errors/AppError";
import endPointQuery from "./EndPointQuery";
import { getWbot } from "../libs/wbot";

export const GetWbotMessage = async (
  ticket: Ticket,
  messageId: string
): Promise<WbotMessage | any> => {



  let limit = 20;

  const wbot_url = await getWbot(ticket.whatsappId);

  const msgFound = await endPointQuery(`${wbot_url}/api/getWbotMessage`, {
    number: `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`,
    messageId: messageId,
    limit: limit
  })

  // console.log('----------> msgFound: ', msgFound)  
  

  // const wbot = await GetTicketWbot(ticket);

 /* const wbotChat = await wbot.getChatById(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);

  const fetchWbotMessagesGradually = async (): Promise<void | WbotMessage> => {
    
    const chatMessages = await wbotChat.fetchMessages({ limit });

    const msgFound = chatMessages.find(msg => msg.id.id === messageId);

    if (!msgFound && limit < 100) {
      limit += 20;
      return fetchWbotMessagesGradually();
    }

    return msgFound;
  };*/

  try {
    // const msgFound = await fetchWbotMessagesGradually();

    if (!msgFound) {
      throw new Error("Cannot found message within 100 last messages");
    }

    return msgFound.data.data;
  } catch (err) {
    throw new AppError("ERR_FETCH_WAPP_MSG");
  }
};

export default GetWbotMessage;
