"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 UserQueue_1 = __importDefault(require("../models/UserQueue"));
const WhatsappQueue_1 = __importDefault(require("../models/WhatsappQueue"));
const Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const sequelize_1 = require("sequelize");
const wbotByUserQueue = ({ userId, status = "CONNECTED", queueId }) => __awaiter(void 0, void 0, void 0, function* () {
    let defaultWhatsapp = [];
    try {
        let query = {};
        query = { userId };
        if (queueId) {
            query = Object.assign(Object.assign({}, query), { queueId });
        }
        const queue = yield UserQueue_1.default.findOne({
            where: query,
            raw: true,
            attributes: ["queueId"]
        });
        if (queue === null || queue === void 0 ? void 0 : queue.queueId) {
            // Pega todas conexões de whatsaap que estão adicionadas à uma fila
            const whatsappQueues = yield WhatsappQueue_1.default.findAll({
                where: { queueId: `${queue === null || queue === void 0 ? void 0 : queue.queueId}` },
                raw: true,
                attributes: ["whatsappId"]
            });
            defaultWhatsapp = yield Whatsapp_1.default.findAll({
                where: {
                    id: {
                        [sequelize_1.Op.in]: whatsappQueues.map(w => {
                            return w.whatsappId;
                        })
                    },
                    status: status
                }
            });
        }
    }
    catch (err) {
        console.log("There was an error on select a whatsapp id by user queue: ", err);
    }
    return defaultWhatsapp;
});
exports.default = wbotByUserQueue;
