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

import { writeFile } from "fs";

import whatsappOfficialAPI from "./WhatsappOfficialAPI";
import path, { join } from "path";
import { promisify } from "util";

import mime from "mime";

import fs from "fs";
import { response } from "express";

const writeFileAsync = promisify(writeFile);

async function receiveWhatsAppMediaOfficialAPI(
  mediaId: string,
  phoneNumberId: string
) {
  try {
    const { data } = await whatsappOfficialAPI.get(
      `/${process.env.VERSION}/${mediaId}?phone_number_id=${phoneNumberId}`
    );

    if (data && data?.url) {
      const config: any = {
        headers: {
          Authorization: `Bearer ${process.env.TOKEN}`
        },
        responseType: "arraybuffer"
      };

      const filename = Date.now() + String(Math.floor(Math.random() * 1000));

      const response = await axios.get(data.url, config);

      const ext = response.headers["content-type"].split("/")[1];

      const filename_ext = `${filename}.${ext}`; 

      const destPath = path.join(
        __dirname,
        `..`,
        `..`,
        `..`,
        `..`,
        `public`,
        `${filename_ext}`
      );

      fs.writeFileSync(destPath, response.data);

      return filename_ext;
    }
  } catch (error) {
    console.log(
      "There was an error on receiveWhatsAppMediaOfficialAPI: ",
      error
    );
  }

  return null;
}

export default receiveWhatsAppMediaOfficialAPI;
