import { MessageMedia } from "whatsapp-web.js";
import { getIO } from "../libs/socket";
import Contact from "../models/Contact";
import Ticket from "../models/Ticket";
import {
  isValidMsg,
  mediaTypeWhatsappOfficial,
  verifyMediaMessage,
  verifyMessage
} from "../services/WbotServices/wbotMessageListener";

import ffmpeg from "fluent-ffmpeg";
import fs from "fs";

import whatsappOfficialAPI from "./WhatsappOfficialAPI";
import path from "path";

import { convertAudioToOgg } from "../helpers/ConvertAudio";
import { bytesToMB } from "./BytesToMB";
import isThisHour from "date-fns/esm/isThisHour/index";
import AppError from "../errors/AppError";

async function sendWhatsMediaOfficialAPI(
  ticket: Ticket,
  media: any,
  type: any,
  mic_audio?: any
) {
  const { contactId, phoneNumberId } = ticket;

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

  const { number } = contact;

  let { filename } = MessageMedia.fromFilePath(media.path);

  const { originalname } = media;

  console.log("mic_audio: ", mic_audio);

  if (type == "audio" && mic_audio) {
    const inputFile = media.path;

    const fileNameWithoutExtension = path.basename(
      media.path,
      path.extname(media.path)
    );

    const outputFile = `${
      inputFile.split(fileNameWithoutExtension)[0]
    }${fileNameWithoutExtension}`;

    try {
      await convertAudioToOgg(inputFile, outputFile);
      media = MessageMedia.fromFilePath(`${outputFile}.ogg`);
      filename = media.filename;
    } catch (error) {
      console.error("Conversion failed:", error);
    }
  }

  let data: any = {
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: number,
    type,
    [type]: {
      link: `${process.env.URL_WHATSAPP_MEDIA}/${filename}`
    }
  };

  if (type == "document") {
    data.document = { ...data.document, filename: originalname };
  }

  console.log("PAYLOAD MEDIA: ", data);

  if (!isValidMsg({ type })) {
    return;
  }

  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 },
        ticketId: ticket.id,
        body: filename,
        fromMe: true,
        read: false,
        phoneNumberId
      };

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

export default sendWhatsMediaOfficialAPI;
