"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 Ticket_1 = __importDefault(require("../../models/Ticket"));
const AppError_1 = __importDefault(require("../../errors/AppError"));
const Contact_1 = __importDefault(require("../../models/Contact"));
const User_1 = __importDefault(require("../../models/User"));
const Queue_1 = __importDefault(require("../../models/Queue"));
const Message_1 = __importDefault(require("../../models/Message"));
const sequelize_1 = require("sequelize");
const sequelize_2 = require("sequelize");
const dbConfig = require("../../config/database");
const sequelize = new sequelize_2.Sequelize(dbConfig);
const Whatsapp_1 = __importDefault(require("../../models/Whatsapp"));
//Report by user, startDate, endDate
const ShowTicketReport = ({ userId, startDate, endDate, pageNumber = "1", createdOrUpdated = "created", queueId }) => __awaiter(void 0, void 0, void 0, function* () {
    // let where_clause: any = {};
    // let query = "";
    // if (userId !== "0") {
    //   where_clause.userid = userId;
    //   query = `AND t.userId = ${userId}`;
    // }
    // if (queueId) {
    //   where_clause.queueId = queueId;
    //   query = `AND t.queueId = ${queueId}`;
    // }
    const createdAtOrUpdatedAt = createdOrUpdated == "created" ? "createdAt" : "updatedAt";
    let where_clause = {};
    if (queueId) {
        where_clause = {
            queueId: queueId,
            [createdAtOrUpdatedAt]: {
                [sequelize_1.Op.gte]: startDate + " 00:00:00.000000",
                [sequelize_1.Op.lte]: endDate + " 23:59:59.999999"
            }
        };
    }
    else if (userId == "0") {
        where_clause = {
            [createdAtOrUpdatedAt]: {
                [sequelize_1.Op.gte]: startDate + " 00:00:00.000000",
                [sequelize_1.Op.lte]: endDate + " 23:59:59.999999"
            }
        };
    }
    else if (userId != "0") {
        where_clause = {
            userid: userId,
            [createdAtOrUpdatedAt]: {
                [sequelize_1.Op.gte]: startDate + " 00:00:00.000000",
                [sequelize_1.Op.lte]: endDate + " 23:59:59.999999"
            }
        };
    }
    const limit = 40;
    const offset = limit * (+pageNumber - 1);
    let { count, rows: tickets } = yield Ticket_1.default.findAndCountAll({
        where: where_clause,
        limit,
        offset,
        attributes: [
            "id",
            "status",
            "statusChatEnd",
            "isRemote",
            [
                sequelize_2.Sequelize.fn("DATE_FORMAT", sequelize_2.Sequelize.col("Ticket.createdAt"), "%d/%m/%Y %H:%i:%s"),
                "createdAt"
            ],
            [
                sequelize_2.Sequelize.fn("DATE_FORMAT", sequelize_2.Sequelize.col("Ticket.updatedAt"), "%d/%m/%Y %H:%i:%s"),
                "updatedAt"
            ]
        ],
        include: [
            {
                model: Message_1.default,
                required: true,
                separate: true,
                attributes: [
                    "body",
                    "read",
                    "mediaType",
                    "fromMe",
                    "mediaUrl",
                    [
                        sequelize_2.Sequelize.fn("DATE_FORMAT", sequelize_2.Sequelize.col("createdAt"), "%d/%m/%Y %H:%i:%s"),
                        "createdAt"
                    ]
                ],
                order: [["createdAt", "ASC"]]
            },
            {
                model: Contact_1.default,
                attributes: ["name", "number"]
            },
            {
                model: User_1.default,
                attributes: ["name", "email"]
            },
            {
                model: Queue_1.default,
                attributes: ["name"]
            },
            {
                model: Whatsapp_1.default,
                attributes: ["name"]
            }
        ],
        order: [["updatedAt", "DESC"]]
    });
    const hasMore = count > offset + tickets.length;
    if (!tickets) {
        throw new AppError_1.default("ERR_NO_TICKET_FOUND", 404);
    }
    if (tickets.length > 0) {
        const waiting_time = yield sequelize.query(`SELECT t.id as ticketId, t.status, TIME_FORMAT(
        SEC_TO_TIME(
                TIMESTAMPDIFF(
                    SECOND,
                    (
                        SELECT createdAt
                        FROM Messages
                        WHERE ticketId = m.ticketId
                        AND fromMe = 0
                        ORDER BY createdAt ASC
                        LIMIT 1
                    ),
                    (
                        SELECT createdAt
                        FROM Messages
                        WHERE ticketId = m.ticketId
                        AND fromAgent = 1
                        ORDER BY createdAt ASC
                        LIMIT 1
                    )
                )
        ), '%H:%i:%s') AS WAITING_TIME
    FROM Tickets t
    JOIN Messages m ON t.id = m.ticketId
    JOIN Whatsapps w ON t.whatsappId = w.id
    JOIN Queues q ON q.id = t.queueId
    WHERE DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
      AND t.id IN (${tickets.map((t) => t.id).join()})
      AND m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id)
      AND m.fromMe = 0
      AND t.status IN ('open', 'closed')
      HAVING WAITING_TIME IS NOT NULL
     ORDER BY
        WAITING_TIME;`, { type: sequelize_1.QueryTypes.SELECT });
        for (let w of waiting_time) {
            const { ticketId, status, WAITING_TIME } = w;
            const index = tickets.findIndex((t) => +(t === null || t === void 0 ? void 0 : t.id) == +ticketId);
            if (index != -1) {
                tickets[index].dataValues.waiting_time = WAITING_TIME;
            }
        }
    }
    return { tickets, count, hasMore };
});
exports.default = ShowTicketReport;
