"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 AppError_1 = __importDefault(require("../../errors/AppError"));
const CheckContactOpenTickets_1 = __importDefault(require("../../helpers/CheckContactOpenTickets"));
const GetDefaultWhatsApp_1 = __importDefault(require("../../helpers/GetDefaultWhatsApp"));
const Ticket_1 = __importDefault(require("../../models/Ticket"));
const ShowContactService_1 = __importDefault(require("../ContactServices/ShowContactService"));
const socket_1 = require("../../libs/socket");
const format_1 = __importDefault(require("date-fns/format"));
const pt_BR_1 = __importDefault(require("date-fns/locale/pt-BR"));
const SplitDateTime_1 = require("../../helpers/SplitDateTime");
const OnlineReporEmiterInfoByUser_1 = __importDefault(require("../../helpers/OnlineReporEmiterInfoByUser"));
const TicketCache_1 = require("../../helpers/TicketCache");
const User_1 = __importDefault(require("../../models/User"));
const whatsappQueueMatchingUserQueue_1 = __importDefault(require("../../helpers/whatsappQueueMatchingUserQueue"));
const Whatsapp_1 = __importDefault(require("../../models/Whatsapp"));
let flatten = require("flat");
const CreateTicketService = ({ contactId, status, userId, queueId = undefined, whatsappId }) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        let defaultWhatsapp;
        if (whatsappId) {
            defaultWhatsapp = yield Whatsapp_1.default.findByPk(whatsappId);
        }
        else {
            defaultWhatsapp = yield GetDefaultWhatsApp_1.default({ userId, queueId });
        }
        // if (queueId) {
        //   const whatsappsByQueue = await ListWhatsAppsForQueueService(queueId);
        //   const exist = await CheckContactOpenTickets(
        //     contactId,
        //     defaultWhatsapp.id,
        //     true
        //   );
        //   console.log(
        //     "whatsappsByQueue: ",
        //     JSON.stringify(whatsappsByQueue, null, 6)
        //   );
        //   if (exist) {
        //     console.log("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
        //   }
        //   return new Ticket();
        // }
        // console.log(JSON.stringify(defaultWhatsapp, null, 2));
        // throw new AppError("test error");
        const { phoneNumberId } = defaultWhatsapp;
        const user = yield User_1.default.findByPk(userId, { raw: true });
        if (!queueId) {
            const matchingQueue = yield whatsappQueueMatchingUserQueue_1.default(userId, defaultWhatsapp, user === null || user === void 0 ? void 0 : user.profile);
            queueId = matchingQueue ? matchingQueue.queueId : undefined;
        }
        console.log("xxxxxxxxxxxx contactId: ", contactId, " | defaultWhatsapp.id: ", defaultWhatsapp.id);
        yield CheckContactOpenTickets_1.default(contactId, defaultWhatsapp.id);
        const { isGroup } = yield ShowContactService_1.default(contactId);
        const { id } = yield defaultWhatsapp.$create("ticket", {
            contactId,
            status,
            isGroup,
            userId,
            queueId,
            phoneNumberId
        });
        const ticket = yield Ticket_1.default.findByPk(id, { include: ["contact"] });
        if (!ticket) {
            throw new AppError_1.default("ERR_CREATING_TICKET");
        }
        // console.log('CONTACT ticket.id: ', ticket.id)
        // TEST DEL
        try {
            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"];
            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 from user: ", error);
        }
        //
        const dateToday = SplitDateTime_1.splitDateTime(new Date(format_1.default(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: pt_BR_1.default })));
        OnlineReporEmiterInfoByUser_1.default(userId.toString(), dateToday.fullDate, dateToday.fullDate);
        const io = socket_1.getIO();
        io.emit("ticketStatus", {
            action: "update",
            ticketStatus: { ticketId: ticket.id, status: ticket.status }
        });
        return ticket;
    }
    catch (error) {
        console.error("===> Error on CreateTicketService.ts file: \n", error);
        throw new AppError_1.default(error.message);
    }
});
exports.default = CreateTicketService;
