"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 date_fns_1 = require("date-fns");
const sequelize_1 = require("sequelize");
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 ListWhatsAppsNumber_1 = __importDefault(require("../WhatsappService/ListWhatsAppsNumber"));
const WhaticketSettings_1 = require("../../helpers/WhaticketSettings");
const FindOrCreateTicketService = (contact, whatsappId, unreadMessages, groupContact, queueId, isRemote) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        let ticket;
        if (((_a = WhaticketSettings_1.getSettingValue("oneContactChatWithManyWhats")) === null || _a === void 0 ? void 0 : _a.value) == "enabled") {
            let whats = yield ListWhatsAppsNumber_1.default(whatsappId);
            ticket = yield Ticket_1.default.findOne({
                where: {
                    status: {
                        [sequelize_1.Op.or]: ["open", "pending", "queueChoice"]
                    },
                    contactId: groupContact ? groupContact.id : contact.id,
                    whatsappId: { [sequelize_1.Op.in]: whats.whatsapps.map((w) => w.id) }
                }
            });
        }
        else {
            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);
        const botInfo = { isOnQueue: false };
        if (ticket) {
            yield ticket.update({ unreadMessages });
        }
        if (!ticket && groupContact) {
            ticket = yield Ticket_1.default.findOne({
                where: {
                    contactId: groupContact.id
                },
                order: [["updatedAt", "DESC"]]
            });
            if (ticket) {
                yield ticket.update({
                    status: "pending",
                    userId: null,
                    unreadMessages
                });
            }
        }
        if (!ticket && !groupContact) {
            ticket = yield Ticket_1.default.findOne({
                where: {
                    updatedAt: {
                        // Tempo osioso para a ura responder  thuanny
                        //[Op.between]: [+subMinutes(new Date(), 30), +new Date()]
                        // Sub seconds
                        [sequelize_1.Op.between]: [+date_fns_1.subSeconds(new Date(), 0), +new Date()]
                    },
                    contactId: contact.id
                },
                order: [["updatedAt", "DESC"]]
            });
            if (ticket) {
                yield ticket.update({
                    status: "pending",
                    userId: null,
                    unreadMessages
                });
            }
        }
        if (!ticket) {
            let status = "pending";
            if (queues.length > 1 && !botInfo.isOnQueue && !queueId) {
                status = "queueChoice";
            }
            ticket = yield Ticket_1.default.create({
                contactId: groupContact ? groupContact.id : contact.id,
                status: status,
                isGroup: !!groupContact,
                queueId,
                unreadMessages,
                whatsappId,
                phoneNumberId,
                isRemote
            });
        }
        ticket = yield ShowTicketService_1.default(ticket.id);
        return ticket;
    }
    catch (error) {
        console.error("===> Error on FindOrCreateTicketService.ts file: \n", error);
        throw new AppError_1.default(error.message);
    }
});
exports.default = FindOrCreateTicketService;
