"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 CheckContactOpenTickets_1 = __importDefault(require("../../helpers/CheckContactOpenTickets"));
const socket_1 = require("../../libs/socket");
const ShowTicketService_1 = __importDefault(require("./ShowTicketService"));
const TicketCache_1 = require("../../helpers/TicketCache");
const AppError_1 = __importDefault(require("../../errors/AppError"));
const SendWhatsappMessageSocket_1 = __importDefault(require("../../helpers/SendWhatsappMessageSocket"));
const BotIsOnQueue_1 = __importDefault(require("../../helpers/BotIsOnQueue"));
const RedisClient_1 = require("../../helpers/RedisClient");
var flatten = require("flat");
const UpdateTicketService = ({ ticketData, ticketId, msg = "" }) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    try {
        const { status, userId, queueId, statusChatEnd, unreadMessages, statusChatEndId, whatsappId, isRemote } = ticketData;
        const ticket = yield ShowTicketService_1.default(ticketId);
        const botInfo = yield BotIsOnQueue_1.default("botqueue");
        if (status == "closed" ||
            (status == "open" && ticket && `${userId}` != `${botInfo.userIdBot}`)) {
            RedisClient_1.deleteObject(`${ticket.whatsappId}`, `${ticket.contactId}`, "ura");
        }
        const oldStatus = ticket.status;
        const oldUserId = (_a = ticket.user) === null || _a === void 0 ? void 0 : _a.id;
        if (oldStatus === "closed") {
            yield CheckContactOpenTickets_1.default(ticket.contact.id, ticket.whatsappId);
        }
        if (status == "closed") {
            RedisClient_1.del(`remote:ticketId:${ticket.id}`);
            let ticketsIds = yield RedisClient_1.get({ key: `remote:controll`, parse: true });
            if (ticketsIds) {
                const index = ticketsIds.findIndex((t) => t == ticket.id);
                console.log("ticketsIds 1: ", ticketsIds);
                if (index != -1) {
                    ticketsIds.splice(index, 1);
                    console.log("ticketsIds 2: ", ticketsIds);
                    RedisClient_1.set(`remote:controll`, JSON.stringify(ticketsIds));
                }
            }
        }
        yield ticket.update({
            status,
            queueId,
            userId,
            unreadMessages,
            statusChatEnd,
            statusChatEndId,
            whatsappId,
            isRemote
        });
        yield ticket.reload();
        if ((msg === null || msg === void 0 ? void 0 : msg.trim().length) > 0) {
            setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
                SendWhatsappMessageSocket_1.default(ticket, `\u200e${msg}`);
            }), 2000);
        }
        // TEST DEL
        try {
            // const { name, number } = await ShowContactService(ticket.contactId)
            let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
            let ticket_obj = JSON.parse(jsonString); //to make plain json
            delete ticket_obj["contact"]["extraInfo"];
            delete ticket_obj["user"];
            ticket_obj = flatten(ticket_obj);
            yield TicketCache_1.createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
        }
        catch (error) {
            console.log("There was an error on UpdateTicketService.ts on createTicketCache: ", error);
        }
        //
        let io = socket_1.getIO();
        if (ticket.status !== oldStatus || ((_b = ticket.user) === null || _b === void 0 ? void 0 : _b.id) !== oldUserId) {
            io.to(oldStatus).emit("ticket", {
                action: "delete",
                ticketId: ticket.id
            });
        }
        io.to(ticket.status)
            .to("notification")
            .to(ticketId.toString())
            .emit("ticket", {
            action: "update",
            ticket
        });
        io.emit("ticketStatus", {
            action: "update",
            ticketStatus: { ticketId: ticket.id, status: ticket.status }
        });
        return { ticket, oldStatus, oldUserId };
    }
    catch (error) {
        console.error("===> Error on UpdateTicketService.ts file: \n", error);
        throw new AppError_1.default(error.message);
    }
});
exports.default = UpdateTicketService;
