import { Op, Sequelize } from "sequelize";
import QuickAnswer from "../../models/QuickAnswer";
import Queue from "../../models/Queue";
import QueuesByUser from "../UserServices/ShowQueuesByUser";
import quickAnswearByQueueFiltered from "../../helpers/QuickAnswearByqueueFiltered";
import { getSettingValue } from "../../helpers/WhaticketSettings";

interface Request {
  searchParam?: string;
  pageNumber?: string;
  userId?: string | number;
}

interface Response {
  quickAnswers: QuickAnswer[];
  count: number;
  hasMore: boolean;
}

const ListQuickAnswerService = async ({
  searchParam = "",
  pageNumber = "1",
  userId
}: Request): Promise<Response> => {
  console.log("searchParam: ", searchParam);

  const whereCondition = {
    message: Sequelize.where(
      Sequelize.fn("LOWER", Sequelize.col("message")),
      "LIKE",
      `%${searchParam.toLowerCase().trim()}%`
    )
  };

  const limit = 20;
  const offset = limit * (+pageNumber - 1);

  let { count, rows: quickAnswers } = await QuickAnswer.findAndCountAll({
    where: whereCondition,

    include: [
      {
        model: Queue,
        as: "queues",
        attributes: ["id", "name", "color", "greetingMessage"]
      }
    ],

    limit,
    offset,
    order: [["message", "ASC"]]
  });

  const hasMore = count > offset + quickAnswers.length;

  if (getSettingValue("quickAnswerByQueue")?.value == "enabled") {
    const queueIds = await QueuesByUser({ userId });
    quickAnswers = quickAnswearByQueueFiltered(queueIds, quickAnswers);
  }

  return {
    quickAnswers,
    count,
    hasMore
  };
};

export default ListQuickAnswerService;
