"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 dbConfig = require("../../config/database");
const sequelize = new sequelize_1.Sequelize(dbConfig);
const { QueryTypes } = require("sequelize");
const Whatsapp_1 = __importDefault(require("../../models/Whatsapp"));
const ShowWhatsAppService_1 = __importDefault(require("../WhatsappService/ShowWhatsAppService"));
const ReportByNumberQueueService = ({ startDate, endDate, queue = false, isRemote = false }) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    let reportServiceData = [];
    const includeIsRemote = isRemote ? "t.isRemote = true AND" : "";
    const whatsapps = yield Whatsapp_1.default.findAll();
    if (!queue) {
        for (const whatsapp of whatsapps) {
            const { id, name, number } = whatsapp;
            let startedByClient;
            let avgChatWaitingTime;
            let pendingChat;
            let closedChat;
            if (!number ||
                reportServiceData.findIndex((w) => (w === null || w === void 0 ? void 0 : w.number) == number) != -1)
                continue;
            console.log("NUMBER: ", number);
            // CHAT STARTED BY AGENT
            const startedByAgent = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999' 
        AND m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromAgent = 1 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            if (!isRemote) {
                // CHAT STARTED BY CLIENT
                startedByClient = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromMe = 0 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            else {
                // CHAT RESPONSE BY CLIENT
                startedByClient = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
        AND m.createdAt = (SELECT MAX(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromMe = 0 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            if (!isRemote) {
                // CHAT CLOSED
                closedChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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.status = 'closed' 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            else {
                // CHAT CLOSED
                closedChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        FROM Tickets t  
        JOIN Whatsapps w ON t.whatsappId = w.id
        JOIN Queues q ON q.id = t.queueId
        WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
        AND t.status = 'closed' 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            if (!isRemote) {
                // CHAT WAINTING TIME
                avgChatWaitingTime = yield sequelize.query(`
        SELECT  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 m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
          AND m.fromMe = 0 
          -- AND q.id = 2  
          AND w.number = ${number} 
          AND t.status IN ('open', 'closed')
          HAVING WAITING_TIME IS NOT NULL
        ORDER BY 
            WAITING_TIME;`, { type: QueryTypes.SELECT });
            }
            if (!isRemote) {
                // CHAT PENDING
                pendingChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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.status = 'pending' 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            else {
                // CHAT PENDING REMOTE
                pendingChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        FROM Tickets t  
        JOIN Whatsapps w ON t.whatsappId = w.id
        JOIN Queues q ON q.id = t.queueId
        WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
        AND t.status = 'pending' 
        AND w.number = ${number};`, { type: QueryTypes.SELECT });
            }
            reportServiceData.push({
                id,
                name,
                number,
                startedByAgent: (_a = startedByAgent[0]) === null || _a === void 0 ? void 0 : _a.ticket_count,
                startedByClient: startedByClient ? (_b = startedByClient[0]) === null || _b === void 0 ? void 0 : _b.ticket_count : 0,
                closedChat: (_c = closedChat[0]) === null || _c === void 0 ? void 0 : _c.ticket_count,
                avgChatWaitingTime: avgChatWaitingTime ? avg(avgChatWaitingTime) : 0,
                pendingChat: (_d = pendingChat[0]) === null || _d === void 0 ? void 0 : _d.ticket_count
            });
        }
    }
    else {
        for (const whatsapp of whatsapps) {
            const { id, name, number } = whatsapp;
            let startedByClient;
            let avgChatWaitingTime;
            let pendingChat;
            let closedChat;
            if (!number ||
                reportServiceData.findIndex((w) => (w === null || w === void 0 ? void 0 : w.number) == number) != -1)
                continue;
            const data = yield ShowWhatsAppService_1.default(id);
            const queues = data.queues.map((q) => {
                const { id, name, color } = q;
                return { id, name, color };
            });
            console.log("NUMBER 2: ", number);
            for (const q of queues) {
                // CHAT STARTED BY AGENT
                const startedByAgent = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999' 
        AND m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromAgent = 1 
        AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                if (!isRemote) {
                    // CHAT STARTED BY CLIENT
                    startedByClient = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromMe = 0 
        AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                else {
                    // CHAT RESPONSE BY CLIENT
                    startedByClient = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
        AND m.createdAt = (SELECT MAX(createdAt) FROM Messages WHERE ticketId = t.id) 
        AND m.fromMe = 0 
        AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                if (!isRemote) {
                    // CHAT CLOSED
                    closedChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
            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.status = 'closed' 
          AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                else {
                    // CHAT CLOSED REMOTE
                    closedChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
            FROM Tickets t  
            JOIN Whatsapps w ON t.whatsappId = w.id
            JOIN Queues q ON q.id = t.queueId
            WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
            AND t.status = 'closed' 
            AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                if (!isRemote) {
                    // CHAT WAINTING TIME
                    avgChatWaitingTime = yield sequelize.query(`SELECT 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 m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) 
          AND m.fromMe = 0  
          AND q.id = ${q.id}
          AND t.status IN ('open', 'closed')
          HAVING WAITING_TIME IS NOT NULL
          ORDER BY 
              WAITING_TIME;`, { type: QueryTypes.SELECT });
                }
                if (!isRemote) {
                    // CHAT PENDING
                    pendingChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        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.status = 'pending' 
        AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                else {
                    // CHAT PENDING REMOTE
                    pendingChat = yield sequelize.query(`SELECT COUNT(DISTINCT t.id) AS ticket_count       
        FROM Tickets t  
        JOIN Whatsapps w ON t.whatsappId = w.id
        JOIN Queues q ON q.id = t.queueId
        WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'  
        AND t.status = 'pending' 
        AND q.id = ${q.id};`, { type: QueryTypes.SELECT });
                }
                reportServiceData.push({
                    id,
                    name,
                    number,
                    queueName: q.name,
                    queueColor: q.color,
                    startedByAgent: (_e = startedByAgent[0]) === null || _e === void 0 ? void 0 : _e.ticket_count,
                    startedByClient: startedByClient
                        ? (_f = startedByClient[0]) === null || _f === void 0 ? void 0 : _f.ticket_count : 0,
                    closedChat: (_g = closedChat[0]) === null || _g === void 0 ? void 0 : _g.ticket_count,
                    avgChatWaitingTime: avgChatWaitingTime ? avg(avgChatWaitingTime) : 0,
                    pendingChat: (_h = pendingChat[0]) === null || _h === void 0 ? void 0 : _h.ticket_count
                });
            }
        }
    }
    return reportServiceData;
});
exports.default = ReportByNumberQueueService;
function avg(avgChatWaitingTime) {
    let waitingAVG = avgChatWaitingTime
        .filter((t) => t === null || t === void 0 ? void 0 : t.WAITING_TIME)
        .map((t) => t.WAITING_TIME);
    if (waitingAVG.length > 0) {
        let midIndex = Math.floor((0 + waitingAVG.length) / 2);
        if (waitingAVG.length % 2 == 1) {
            waitingAVG = waitingAVG[midIndex];
        }
        else {
            waitingAVG = calculateAverageTime(waitingAVG[midIndex - 1], waitingAVG[midIndex]);
        }
    }
    else {
        waitingAVG = 0;
    }
    return waitingAVG;
}
function calculateAverageTime(time1, time2) {
    // Function to parse time string to seconds
    function timeStringToSeconds(timeString) {
        const [hours, minutes, seconds] = timeString.split(":").map(Number);
        return hours * 3600 + minutes * 60 + seconds;
    }
    // Function to convert seconds to time string
    function secondsToTimeString(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;
        return `${hours.toString().padStart(2, "0")}:${minutes
            .toString()
            .padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
    }
    // Convert time strings to seconds
    const time1Seconds = timeStringToSeconds(time1);
    const time2Seconds = timeStringToSeconds(time2);
    // Calculate average seconds
    const averageSeconds = Math.round((time1Seconds + time2Seconds) / 2);
    // Convert average seconds back to time string
    const averageTime = secondsToTimeString(averageSeconds);
    return averageTime;
}
