import { subSeconds } from "date-fns";
import Message from "../models/Message";

import { Op, Sequelize } from "sequelize";

const mostRepeatedPhrase = async (
  ticketId: number | string,
  fromMe: boolean = false
) => {
  let res: any = { body: "", occurrences: 0 };

  try {
    const mostRepeatedPhrase: any = await Message.findOne({
      where: {
        ticketId: ticketId,
        fromMe: fromMe ? fromMe : 0,
        body: {
          [Op.notRegexp]: "^[0-9]+$"
        },
        updatedAt: {
          [Op.between]: [+subSeconds(new Date(), 150), +new Date()]
        }
      },
      attributes: [
        "body",
        [Sequelize.fn("COUNT", Sequelize.col("body")), "occurrences"]
      ],

      group: ["body"],
      order: [[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 };
};

export default mostRepeatedPhrase;
