"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 sequelize_1 = require("sequelize");
const BotIsOnQueue_1 = __importDefault(require("../../helpers/BotIsOnQueue"));
const Ticket_1 = __importDefault(require("../../models/Ticket"));
const ShowWhatsAppService_1 = __importDefault(require("../WhatsappService/ShowWhatsAppService"));
const ShowTicketService_1 = __importDefault(require("./ShowTicketService"));
const AppError_1 = __importDefault(require("../../errors/AppError"));
const ShowQueueService_1 = __importDefault(require("../QueueService/ShowQueueService"));
const UpdateTicketService_1 = __importDefault(require("./UpdateTicketService"));
const FindOrCreateTicketServiceBot = (contact, whatsappId, unreadMessages, groupContact) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        let ticket = yield Ticket_1.default.findOne({
            where: {
                status: {
                    [sequelize_1.Op.or]: ["open", "pending", "queueChoice"]
                },
                contactId: groupContact ? groupContact.id : contact.id
            }
        });
        const { queues, greetingMessage, phoneNumberId } = yield ShowWhatsAppService_1.default(whatsappId);
        //Habilitar esse caso queira usar o bot
        const botInfo = yield BotIsOnQueue_1.default('botqueue');
        // const botInfo = { isOnQueue: false }
        if (ticket) {
            yield ticket.update({ unreadMessages });
        }
        // if (!ticket && groupContact) {
        //     ticket = await Ticket.findOne({
        //         where: {
        //             contactId: groupContact.id
        //         },
        //         order: [["updatedAt", "DESC"]]
        //     });
        //     if (ticket) {
        //         await ticket.update({
        //             status: "pending",
        //             userId: null,
        //             unreadMessages
        //         });
        //     }
        // }
        if (!ticket && !groupContact) {
            console.log('BOT CREATING OR REOPENING THE TICKET');
            ticket = yield Ticket_1.default.findOne({
                where: {
                    contactId: contact.id,
                    userId: botInfo.userIdBot
                },
                order: [["updatedAt", "DESC"]]
            });
            if (ticket) {
                yield ticket.update({
                    status: "open",
                    userId: botInfo.userIdBot,
                    unreadMessages
                });
                console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
                yield dialogFlowStartContext(contact, ticket, botInfo);
            }
        }
        let created = false;
        if (!ticket) {
            created = true;
            let status = "open";
            if (queues.length > 1 && !botInfo.isOnQueue) {
                status = "queueChoice";
            }
            ticket = yield Ticket_1.default.create({
                contactId: groupContact ? groupContact.id : contact.id,
                status: status,
                userId: botInfo.userIdBot,
                isGroup: !!groupContact,
                unreadMessages,
                whatsappId,
                phoneNumberId
            });
            console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy');
            yield dialogFlowStartContext(contact, ticket, botInfo);
        }
        ticket = yield ShowTicketService_1.default(ticket.id);
        return { ticket, created };
    }
    catch (error) {
        console.error('===> Error on FindOrCreateTicketServiceBot.ts file: \n', error);
        throw new AppError_1.default(error.message);
    }
});
exports.default = FindOrCreateTicketServiceBot;
function dialogFlowStartContext(contact, ticket, botInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let msg = { type: 'chat', from: `${contact.number}@c.us`, body: '0' };
        let queue = yield ShowQueueService_1.default(botInfo.botQueueId);
        yield UpdateTicketService_1.default({
            ticketData: { queueId: queue.id },
            ticketId: ticket.id
        });
        ticket = yield ShowTicketService_1.default(ticket.id);
        // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
    });
}
