"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 AppError_1 = __importDefault(require("../errors/AppError"));
const Ticket_1 = __importDefault(require("../models/Ticket"));
const User_1 = __importDefault(require("../models/User"));
const ListWhatsAppsNumber_1 = __importDefault(require("../services/WhatsappService/ListWhatsAppsNumber"));
const WhaticketSettings_1 = require("./WhaticketSettings");
const CheckContactOpenTickets = (contactId, whatsappId, handle) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    let ticket;
    if (((_a = WhaticketSettings_1.getSettingValue("oneContactChatWithManyWhats")) === null || _a === void 0 ? void 0 : _a.value) == "enabled") {
        let whats = yield ListWhatsAppsNumber_1.default(whatsappId);
        // console.log("contactId: ", contactId, " | whatsappId: ", whatsappId);
        // console.log("WHATS: ", JSON.stringify(whats, null, 6));
        ticket = yield Ticket_1.default.findOne({
            where: {
                [sequelize_1.Op.and]: [
                    { contactId: contactId },
                    { whatsappId: { [sequelize_1.Op.in]: whats.whatsapps.map((w) => w.id) } },
                    { status: { [sequelize_1.Op.or]: ["open", "pending"] } }
                ]
            }
        });
        console.log("TICKET: ", JSON.stringify(ticket, null, 6));
    }
    else {
        ticket = yield Ticket_1.default.findOne({
            where: { contactId, status: { [sequelize_1.Op.or]: ["open", "pending"] } }
        });
    }
    if (ticket) {
        if (handle)
            return true;
        const userName = yield User_1.default.findOne({
            where: { id: ticket.userId }
        });
        const error = new AppError_1.default("ERR_OTHER_OPEN_TICKET");
        error.message = `Erro: já existe um ticket criado com esse contato. Responsável: ${userName ? userName.name.toUpperCase() : 'Aguardando'}`;
        throw error;
    }
});
exports.default = CheckContactOpenTickets;
