"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const sequelize_1 = require("sequelize");
const dbConfig = require("../../config/database");
const { QueryTypes } = require("sequelize");
const sequelize = new sequelize_1.Sequelize(dbConfig);
const ListWhatsappQueueByUserQueue = (userId, profiles) => __awaiter(void 0, void 0, void 0, function* () {
    const users = yield sequelize.query(`select wq.whatsappId, wq.queueId, uq.userId, uq.queueId, u.id, u.name, u.profile, w.number
from WhatsappQueues wq join UserQueues uq join Users u join Whatsapps w on
wq.queueId = uq.queueId where u.id = uq.userId and u.profile in (${profiles}) and u.id = ${userId} 
and w.id = wq.whatsappId group by w.number ;`, { type: QueryTypes.SELECT });
    return users;
});
const ListWhatsappQueesByUser = (whatsappIds) => __awaiter(void 0, void 0, void 0, function* () {
    const users = yield sequelize.query(`SELECT
    wq.whatsappId, wq.queueId, q.name, q.id, q.name, q.color 
FROM
    WhatsappQueues wq
JOIN
    Queues q ON wq.whatsappId IN (${whatsappIds})  AND q.id = wq.queueId group by wq.queueId;

`, { type: QueryTypes.SELECT });
    return users;
});
const ListUserByWhatsappQueuesService = (userId, profiles) => __awaiter(void 0, void 0, void 0, function* () {
    const whatsapps = yield ListWhatsappQueueByUserQueue(userId, profiles);
    let whatsappIds = whatsapps.map((w) => w.whatsappId);
    if (whatsappIds.length == 0)
        return { users: [], queues: [] };
    console.log("----------> whatsappIds: ", whatsappIds, " | userId: ", userId);
    whatsappIds = whatsappIds.join(", ");
    const users = yield sequelize.query(`select wq.whatsappId, wq.queueId, uq.userId, uq.queueId, u.id, u.name, u.profile
from WhatsappQueues wq join UserQueues uq join Users u on
wq.queueId = uq.queueId where u.id = uq.userId and u.profile in (${profiles}) and wq.whatsappId in (${whatsappIds}) group by u.id;`, { type: QueryTypes.SELECT });
    const queues = yield ListWhatsappQueesByUser(whatsappIds);
    return { users, queues };
});
exports.default = ListUserByWhatsappQueuesService;
