import AppError from "../../errors/AppError";
import endPointQuery from "../../helpers/EndPointQuery";
import GetWbotMessage from "../../helpers/GetWbotMessage";
import { getWbot } from "../../libs/wbot";
import Message from "../../models/Message";
import Ticket from "../../models/Ticket";

const DeleteWhatsAppMessage = async (messageId: string): Promise<Message | any> => {
  const message = await Message.findByPk(messageId, {
    include: [
      {
        model: Ticket,
        as: "ticket",
        include: ["contact"]
      }
    ]
  });
  
  if(message && message?.phoneNumberId){
    throw new AppError("Mensagens enviada pela API Oficial do Whatsapp não são deletadas!");
  }

  if (!message) {
    throw new AppError("No message found with this ID.");
  }

  const { ticket } = message;

  let limit = 20; 

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

  if (messageToDelete && messageToDelete.data.data) {
    await message.update({ isDeleted: true });
  }
  else{
    throw new AppError("ERR_DELETE_WAPP_MSG");
  }


  return message;
};

export default DeleteWhatsAppMessage;
