import { Sequelize, Op } from "sequelize";
import Contact from "../../models/Contact";
import Queue from "../../models/Queue";
import { getSettingValue } from "../../helpers/WhaticketSettings";
// import ListContactsService from "../services/ContactServices/ListContactsService";
import ListWhatsappQueueByUserQueue from "../WhatsappService/ListWhatsAppsForQueueService";
import QueuesByUser from "../UserServices/ShowQueuesByUser";
import { number } from "yup";

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

interface Response {
  contacts: Contact[];
  count: number;
  hasMore: boolean;
}

const ListContactsService = async ({
  searchParam = "",
  pageNumber = "1",
  userId
}: Request): Promise<Response> => {
  const whereCondition = {
    [Op.or]: [
      {
        name: Sequelize.where(
          Sequelize.fn("LOWER", Sequelize.col("Contact.name")),
          "LIKE",
          `%${searchParam.toLowerCase().trim()}%`
        )
      },
      { number: { [Op.like]: `%${searchParam.toLowerCase().trim()}%` } }
    ]
  };
  const limit = 20;
  const offset = limit * (+pageNumber - 1);

  let { count, rows: contacts } = await Contact.findAndCountAll({
    where: whereCondition,
    limit,
    include: [
      {
        model: Queue,
        as: "queues",
        // where: whereConditionQueue,
        attributes: ["id", "name", "color", "greetingMessage"]
      }
    ],
    offset,
    order: [["name", "ASC"]]
  });

  const hasMore = count > offset + contacts.length;

  if (getSettingValue("contactByqueues")?.value == "enabled") {
    const queueIds = await QueuesByUser({ userId });

    contacts = contactQueueFilter(queueIds, contacts);
  }

  return {
    contacts,
    count,
    hasMore
  };
};
export default ListContactsService;

function contactQueueFilter(queueIds: any[], contacts: Contact[]) {
  let auxContact: any[] = [];
  let repet: any[] = [];
  const userQueues = queueIds.map((uq: any) => uq.queueId);

  for (const contact of contacts) {
    const { queues, id } = contact;

    if (queues.length == 0) {
      auxContact.push(contact);
      continue;
    }

    for (const q of queues) {
      if (userQueues.includes(q.id)) {
        if (repet.includes(id)) continue;
        repet.push(id);

        auxContact.push(contact);
      }
    }
  }

  return auxContact;
}
