"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 RedisClient_1 = require("./RedisClient");
function controllByNumber() {
    return __awaiter(this, void 0, void 0, function* () {
        let tickets = yield RedisClient_1.get({ key: "remote:ticketId*", parse: false });
        if (!tickets)
            return { ticketIds: [], tickets: null };
        let controll = [];
        for (const ticket of tickets) {
            let match = ticket.match(/"whatsappId":(\d+)/);
            let whatsappId = match ? match[1] : null;
            const whatsapp = yield RedisClient_1.get({
                key: `whatsapp:${whatsappId}`
            });
            match = whatsapp.match(/"number":"(\d+)"/);
            let number = match ? match[1] : null;
            match = ticket.match(/"id":(\d+)/);
            let ticketId = match ? match[1] : null;
            number = JSON.parse(number);
            ticketId = JSON.parse(ticketId);
            const index = controll.findIndex((c) => c.number == number);
            if (index == -1) {
                controll.push({ ticketId, number });
            }
        }
        const ticketIds = controll.map((c) => c.ticketId);
        RedisClient_1.set(`remote:controll`, JSON.stringify(ticketIds));
        return { ticketIds, tickets };
    });
}
exports.default = controllByNumber;
