"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 fs_1 = __importDefault(require("fs"));
const whatsapp_web_js_1 = require("whatsapp-web.js");
const AppError_1 = __importDefault(require("../../errors/AppError"));
const TicketCache_1 = require("../../helpers/TicketCache");
const SendWhatsappMessageMediaSocket_1 = __importDefault(require("../../helpers/SendWhatsappMessageMediaSocket"));
const sendWhatsMediaOfficialAPI_1 = __importDefault(require("../../helpers/sendWhatsMediaOfficialAPI"));
const wbotMessageListener_1 = require("./wbotMessageListener");
const BytesToMB_1 = require("../../helpers/BytesToMB");
const SendWhatsAppMedia = ({ media, ticket, mic_audio }) => __awaiter(void 0, void 0, void 0, function* () {
    const { phoneNumberId } = ticket;
    if (phoneNumberId) {
        const { type, mbMaxSize } = wbotMessageListener_1.mediaTypeWhatsappOfficial(media.mimetype);
        const filesize = BytesToMB_1.bytesToMB(media.size);
        if (filesize > mbMaxSize) {
            throw new AppError_1.default("FILE TOO LARGE!");
        }
        if (!type) {
            throw new AppError_1.default("FILE TYPE NOT SUPPORTED!");
        }
        sendWhatsMediaOfficialAPI_1.default(ticket, media, type, mic_audio);
        return;
    }
    try {
        const newMedia = whatsapp_web_js_1.MessageMedia.fromFilePath(media.path);
        SendWhatsappMessageMediaSocket_1.default(ticket, newMedia);
        yield ticket.update({ lastMessage: media.filename });
        yield TicketCache_1.updateTicketCacheByTicketId(ticket.id, {
            lastMessage: media.filename,
            updatedAt: new Date(ticket.updatedAt).toISOString()
        });
        console.log("media.path: ", media.path);
        fs_1.default.unlinkSync(media.path);
    }
    catch (err) {
        throw new AppError_1.default("ERR_SENDING_WAPP_MSG");
    }
});
exports.default = SendWhatsAppMedia;
