"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 Message_1 = __importDefault(require("../models/Message"));
const sequelize_1 = require("sequelize");
const mostRepeatedPhrase = (ticketId, fromMe = false) => __awaiter(void 0, void 0, void 0, function* () {
    let res = { body: "", occurrences: 0 };
    try {
        const mostRepeatedPhrase = yield Message_1.default.findOne({
            where: {
                ticketId: ticketId,
                fromMe: fromMe ? fromMe : 0,
                body: {
                    [sequelize_1.Op.notRegexp]: "^[0-9]+$"
                },
                updatedAt: {
                    [sequelize_1.Op.between]: [+date_fns_1.subSeconds(new Date(), 150), +new Date()]
                }
            },
            attributes: [
                "body",
                [sequelize_1.Sequelize.fn("COUNT", sequelize_1.Sequelize.col("body")), "occurrences"]
            ],
            group: ["body"],
            order: [[sequelize_1.Sequelize.literal("occurrences"), "DESC"]],
            limit: 1
        });
        if (mostRepeatedPhrase) {
            const { body, occurrences } = mostRepeatedPhrase.get();
            console.log(`The most repeated phrase is "${body}" with ${occurrences} occurrences.`);
            const isNumber = /^\d+$/.test(body.trim());
            if (!isNumber) {
                return { body, occurrences };
            }
        }
        else {
            console.log("No phrases found.");
        }
    }
    catch (error) {
        console.log("error on MostRepeatedPhrase: ", error);
    }
    return { body: "", occurrences: 0 };
});
exports.default = mostRepeatedPhrase;
