"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 });
exports.remove = exports.store = exports.index = void 0;
const WhatsappOfficialAPI_1 = __importDefault(require("../helpers/WhatsappOfficialAPI"));
const socket_1 = require("../libs/socket");
const ListMessagesService_1 = __importDefault(require("../services/MessageServices/ListMessagesService"));
const ShowTicketService_1 = __importDefault(require("../services/TicketServices/ShowTicketService"));
const DeleteWhatsAppMessage_1 = __importDefault(require("../services/WbotServices/DeleteWhatsAppMessage"));
const SendWhatsAppMedia_1 = __importDefault(require("../services/WbotServices/SendWhatsAppMedia"));
const SendWhatsAppMessage_1 = __importDefault(require("../services/WbotServices/SendWhatsAppMessage"));
const sendWhatsAppMessageOfficialAPI_1 = __importDefault(require("../helpers/sendWhatsAppMessageOfficialAPI"));
const Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const CheckLastClientMsg24hs_1 = __importDefault(require("../helpers/CheckLastClientMsg24hs"));
const AppError_1 = __importDefault(require("../errors/AppError"));
const index = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { ticketId } = req.params;
    const { pageNumber } = req.query;
    const { count, messages, ticket, hasMore } = yield ListMessagesService_1.default({
        pageNumber,
        ticketId
    });
    return res.json({ count, messages, ticket, hasMore });
});
exports.index = index;
const store = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { ticketId } = req.params;
    const { body, quotedMsg, mic_audio, params } = req.body;
    const medias = req.files;
    const ticket = yield ShowTicketService_1.default(ticketId);
    const { queueId } = ticket;
    console.log("-----------> queueId: ", queueId, "  |  quotedMsg: ", quotedMsg, " | params: ", params);
    const { phoneNumberId, whatsappId } = ticket;
    if (phoneNumberId) {
        const into24hs = yield CheckLastClientMsg24hs_1.default(ticket);
        if (into24hs && into24hs.length == 0) {
            if (params) {
                console.log("SEND TEMPLATE PARAMS: ", params);
                // return res.send()
                let payloadComponents = [];
                try {
                    for (let i in params) {
                        const { parameters, language, type } = params[i];
                        if (type == "BODY") {
                            if (parameters && parameters.length > 0) {
                                let components = [{ type: "body", parameters: [] }];
                                for (let x in parameters) {
                                    const { type, text, index } = parameters[x];
                                    console.log(text);
                                    components[0].parameters.splice(index - 1, 0, {
                                        type,
                                        text
                                    });
                                }
                                payloadComponents.push(components[0]);
                            }
                        }
                        else if (type == "BUTTONS") {
                        }
                    }
                    const name = params.find((p) => p === null || p === void 0 ? void 0 : p.template_name);
                    const { language } = (params === null || params === void 0 ? void 0 : params.find((p) => p === null || p === void 0 ? void 0 : p.language)) || "pt_BR";
                    const { template_name } = name;
                    if (template_name && language) {
                        const template = {
                            template: {
                                name: template_name,
                                language: { code: language },
                                components: payloadComponents
                            }
                        };
                        console.log("TEMPLATE: ", template);
                        sendWhatsAppMessageOfficialAPI_1.default(ticket, body, null, template);
                        return res.send();
                    }
                }
                catch (error) {
                    throw new AppError_1.default(error.message);
                }
            }
            else {
                try {
                    const { wabaId } = yield Whatsapp_1.default.findByPk(whatsappId);
                    const { data } = yield WhatsappOfficialAPI_1.default.get(`/${process.env.VERSION}/${wabaId}/message_templates?language=pt_BR`);
                    return res.status(200).json(data);
                }
                catch (error) {
                    return res
                        .status(500)
                        .json({ message: "Não foi possível baixar os templates!" });
                }
            }
        }
    }
    if (medias) {
        yield Promise.all(medias.map((media) => __awaiter(void 0, void 0, void 0, function* () {
            console.log(`\n >>>>>>>>>> SENDING MESSAGE MEDIA
        Parcial ticket info and media: 
        ticket.id: ${ticket.id}
        ticket.status: ${ticket.status}
        ticket.whatsapp.id: ${ticket.whatsappId}
        ticket.contact.number: ${ticket.contact.number}
        ticket.contact.name: ${ticket.contact.name}
        ticket.contact.profilePicUrl: ${ticket.contact.profilePicUrl}
        ticket.user.id: ${ticket.user.id}
        ticket.user.name: ${ticket.user.name}
        media:`, media, "\n");
            yield SendWhatsAppMedia_1.default({ media, ticket, mic_audio });
        })));
    }
    else {
        console.log(`\n >>>>>>>>>> SENDING MESSAGE
    Parcial ticket info: 
    ticket.id: ${ticket.id}
    ticket.status: ${ticket.status}
    ticket.whatsapp.id: ${ticket.whatsappId} 
    ticket.contact.number: ${ticket.contact.number}
    message: ${body}
    ticket.contact.name: ${ticket.contact.name}
    ticket.contact.profilePicUrl: ${ticket.contact.profilePicUrl}
    ticket.user.id: ${ticket.user.id}
    ticket.user.name: ${ticket.user.name}\n`);
        yield SendWhatsAppMessage_1.default({ body, ticket, quotedMsg });
    }
    return res.send();
});
exports.store = store;
const remove = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { messageId } = req.params;
    const message = yield DeleteWhatsAppMessage_1.default(messageId);
    const io = socket_1.getIO();
    io.to(message.ticketId.toString()).emit("appMessage", {
        action: "update",
        message
    });
    return res.send();
});
exports.remove = remove;
