"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const whatsapp_web_js_1 = require("whatsapp-web.js");
const Contact_1 = __importDefault(require("../models/Contact"));
const wbotMessageListener_1 = require("../services/WbotServices/wbotMessageListener");
const WhatsappOfficialAPI_1 = __importDefault(require("./WhatsappOfficialAPI"));
const path_1 = __importDefault(require("path"));
const ConvertAudio_1 = require("../helpers/ConvertAudio");
function sendWhatsMediaOfficialAPI(ticket, media, type, mic_audio) {
    return __awaiter(this, void 0, void 0, function* () {
        const { contactId, phoneNumberId } = ticket;
        const contact = yield Contact_1.default.findByPk(contactId);
        const { number } = contact;
        let { filename } = whatsapp_web_js_1.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_1.default.basename(media.path, path_1.default.extname(media.path));
            const outputFile = `${inputFile.split(fileNameWithoutExtension)[0]}${fileNameWithoutExtension}`;
            try {
                yield ConvertAudio_1.convertAudioToOgg(inputFile, outputFile);
                media = whatsapp_web_js_1.MessageMedia.fromFilePath(`${outputFile}.ogg`);
                filename = media.filename;
            }
            catch (error) {
                console.error("Conversion failed:", error);
            }
        }
        let data = {
            messaging_product: "whatsapp",
            recipient_type: "individual",
            to: number,
            type,
            [type]: {
                link: `${process.env.URL_WHATSAPP_MEDIA}/${filename}`
            }
        };
        if (type == "document") {
            data.document = Object.assign(Object.assign({}, data.document), { filename: originalname });
        }
        console.log("PAYLOAD MEDIA: ", data);
        if (!wbotMessageListener_1.isValidMsg({ type })) {
            return;
        }
        WhatsappOfficialAPI_1.default
            .post(`/${process.env.VERSION}/${phoneNumberId}/messages`, data)
            .then(response => {
            console.log("Response:", response.data);
            let msg = {};
            msg = Object.assign(Object.assign({}, msg), { id: { id: response.data.messages[0].id }, ticketId: ticket.id, body: filename, fromMe: true, read: false, phoneNumberId });
            wbotMessageListener_1.verifyMediaMessage(msg, ticket, contact, media);
        })
            .catch(error => {
            console.log("Error on try request: ", error.response.data.error.message);
        });
    });
}
exports.default = sendWhatsMediaOfficialAPI;
