"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 Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const GetWbotByUserQueue_1 = __importDefault(require("../helpers/GetWbotByUserQueue"));
const LoadBalanceWhatsSameQueue_1 = require("./LoadBalanceWhatsSameQueue");
const GetDefaultWhatsApp = ({ userId, queueId, ignoreNoWhatsappFound = false }) => __awaiter(void 0, void 0, void 0, function* () {
    let defaultWhatsapp = yield Whatsapp_1.default.findOne({
        where: { isDefault: true }
    });
    if (!defaultWhatsapp) {
        if (userId) {
            let whatsapps = yield GetWbotByUserQueue_1.default({ userId, queueId });
            if (userId && queueId) {
                if (whatsapps.length > 1) {
                    let whatsAppOfficial = whatsapps.find((w) => w.phoneNumberId && w.phoneNumberId.trim().length > 0);
                    if (whatsAppOfficial) {
                        return whatsapps;
                    }
                }
            }
            if (whatsapps.length > 0) {
                if (whatsapps.length > 1) {
                    defaultWhatsapp = whatsapps[+LoadBalanceWhatsSameQueue_1.WhatsIndex(whatsapps)];
                }
                else {
                    defaultWhatsapp = whatsapps[0];
                }
            } // Quando o usuário não está em nenhuma fila
            else {
                defaultWhatsapp = yield Whatsapp_1.default.findOne({
                    where: { status: "CONNECTED" }
                });
            }
        }
        else {
            defaultWhatsapp = yield Whatsapp_1.default.findOne({
                where: { status: "CONNECTED", isOfficial: false }
            });
        }
    }
    if (!defaultWhatsapp && !ignoreNoWhatsappFound) {
        throw new AppError_1.default("ERR_NO_DEF_WAPP_FOUND");
    }
    return defaultWhatsapp;
});
exports.default = GetDefaultWhatsApp;
