import fs from "fs";
import { MessageMedia, Message as WbotMessage } from "whatsapp-web.js";
import AppError from "../../errors/AppError";
import GetTicketWbot from "../../helpers/GetTicketWbot";
import Ticket from "../../models/Ticket";

import { updateTicketCacheByTicketId } from "../../helpers/TicketCache";
import { date } from "faker";
import { getIO } from "../../libs/socket";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import sendWhatsAppMediaSocket from "../../helpers/SendWhatsappMessageMediaSocket";
import sendWhatsMediaOfficialAPI from "../../helpers/sendWhatsMediaOfficialAPI";
import { mediaTypeWhatsappOfficial } from "./wbotMessageListener";
import { bytesToMB } from "../../helpers/BytesToMB";

interface Request {
  media: Express.Multer.File;
  ticket: Ticket; 
  mic_audio?: any
}

const SendWhatsAppMedia = async ({
  media,
  ticket,
  mic_audio
}: Request): Promise<WbotMessage | any> => {
  const { phoneNumberId } = ticket;

  if (phoneNumberId) {
    const { type, mbMaxSize }: any = mediaTypeWhatsappOfficial(media.mimetype); 

    const filesize: any = bytesToMB(media.size);

    if (filesize > mbMaxSize) {
      throw new AppError("FILE TOO LARGE!");
    }
    if (!type) {
      throw new AppError("FILE TYPE NOT SUPPORTED!");
    }

    sendWhatsMediaOfficialAPI(ticket, media, type, mic_audio); 
    return;
  }

  try {
    const newMedia = MessageMedia.fromFilePath(media.path);

    sendWhatsAppMediaSocket(ticket, newMedia);

    await ticket.update({ lastMessage: media.filename });

    await updateTicketCacheByTicketId(ticket.id, {
      lastMessage: media.filename,
      updatedAt: new Date(ticket.updatedAt).toISOString()
    });

    console.log("media.path: ", media.path);
    fs.unlinkSync(media.path);
  } catch (err) {
    throw new AppError("ERR_SENDING_WAPP_MSG");
  }
};

export default SendWhatsAppMedia;
