"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 AppError_1 = __importDefault(require("../../errors/AppError"));
const GetWbotMessage_1 = __importDefault(require("../../helpers/GetWbotMessage"));
const SerializeWbotMsgId_1 = __importDefault(require("../../helpers/SerializeWbotMsgId"));
const GetWbotByUserQueue_1 = __importDefault(require("../../helpers/GetWbotByUserQueue"));
const LoadBalanceWhatsSameQueue_1 = require("../../helpers/LoadBalanceWhatsSameQueue");
const TicketCache_1 = require("../../helpers/TicketCache");
const ListWhatsAppsNumber_1 = __importDefault(require("../WhatsappService/ListWhatsAppsNumber"));
// import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
const GetDefaultWhatsApp_1 = __importDefault(require("../../helpers/GetDefaultWhatsApp"));
const SendWhatsappMessageSocket_1 = __importDefault(require("../../helpers/SendWhatsappMessageSocket"));
const sendWhatsAppMessageOfficialAPI_1 = __importDefault(require("../../helpers/sendWhatsAppMessageOfficialAPI"));
const SendWhatsAppMessage = ({ body, ticket, quotedMsg, number }) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { phoneNumberId } = ticket;
        if (phoneNumberId) {
            sendWhatsAppMessageOfficialAPI_1.default(ticket, body, quotedMsg);
            return;
        }
        let timestamp = Date.now() + String(Math.floor(Math.random() * 1000));
        var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`;
        console.time(timetaken);
        let quotedMsgSerializedId;
        if (quotedMsg) {
            yield GetWbotMessage_1.default(ticket, quotedMsg.id);
            quotedMsgSerializedId = SerializeWbotMsgId_1.default(ticket, quotedMsg);
        }
        console.log("quotedMsgSerializedId: ", quotedMsgSerializedId);
        let whatsapps;
        let listWhatsapp = null;
        // listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
        if (!ticket.whatsappId) {
            const defaultWhatsapp = yield GetDefaultWhatsApp_1.default({
                userId: ticket.userId
            });
            yield ticket.update({ whatsappId: +defaultWhatsapp.id });
        }
        if (!listWhatsapp) {
            listWhatsapp = yield ListWhatsAppsNumber_1.default(ticket.whatsappId, "CONNECTED");
        }
        if (listWhatsapp.whatsapp &&
            listWhatsapp.whatsapp.status != "CONNECTED" &&
            listWhatsapp.whatsapps.length > 0) {
            yield ticket.update({ whatsappId: +listWhatsapp.whatsapps[0].id });
        }
        if (listWhatsapp.whatsapps.length > 1) {
            const _whatsapp = listWhatsapp.whatsapps[Math.floor(Math.random() * listWhatsapp.whatsapps.length)];
            yield ticket.update({ whatsappId: +_whatsapp.id });
        }
        if (listWhatsapp.whatsapps.length == 0 &&
            listWhatsapp.whatsapp.status != "CONNECTED") {
            whatsapps = yield GetWbotByUserQueue_1.default({ userId: ticket.userId });
            if (whatsapps.length > 0) {
                whatsapps = whatsapps.filter((w) => !(w === null || w === void 0 ? void 0 : w.isOfficial));
                if (whatsapps.length > 1) {
                    yield ticket.update({
                        whatsappId: whatsapps[+LoadBalanceWhatsSameQueue_1.WhatsIndex(whatsapps)].id
                    });
                }
                else if (whatsapps && whatsapps.length == 1) {
                    yield ticket.update({ whatsappId: whatsapps[0].id });
                }
                else {
                    throw new Error("Sessão de Whatsapp desconectada! Entre em contato com o suporte.");
                }
            }
        }
        console.log("1 --------> send from whatsapp ticket.whatsappId: ", ticket.whatsappId);
        try {
            SendWhatsappMessageSocket_1.default(ticket, body, quotedMsgSerializedId, number);
            yield ticket.update({ lastMessage: body });
            yield TicketCache_1.updateTicketCacheByTicketId(ticket.id, {
                lastMessage: body,
                updatedAt: new Date(ticket.updatedAt).toISOString()
            });
            console.timeEnd(timetaken);
        }
        catch (err) {
            console.error("0 ===> Error on SendWhatsAppMessage.ts file: \n", err);
            throw new AppError_1.default("ERR_SENDING_WAPP_MSG");
        }
    }
    catch (error) {
        console.error("===> Error on SendWhatsAppMessage.ts file: \n", error);
        throw new AppError_1.default(error.message);
    }
});
exports.default = SendWhatsAppMessage;
