import UserQueue from "../models/UserQueue";
import WhatsappQueue from "../models/WhatsappQueue";
import Whatsapp from "../models/Whatsapp";

import { Op, where } from "sequelize";

interface Request {
  userId: string | number;
  status?: string;
  queueId?: string | number;
}

const wbotByUserQueue = async ({
  userId,
  status = "CONNECTED",
  queueId
}: Request): Promise<any> => {
  let defaultWhatsapp: Whatsapp[] = [];

  try {
    let query: any = {};

    query = { userId };

    if (queueId) {
      query = { ...query, queueId };
    } 

    const queue = await UserQueue.findOne({
      where: query,
      raw: true,
      attributes: ["queueId"]
    }); 

    if (queue?.queueId) {
      // Pega todas conexões de whatsaap que estão adicionadas à uma fila
      const whatsappQueues = await WhatsappQueue.findAll({
        where: { queueId: `${queue?.queueId}` },
        raw: true,
        attributes: ["whatsappId"]
      });

      defaultWhatsapp = await Whatsapp.findAll({
        where: {
          id: {
            [Op.in]: whatsappQueues.map(w => {
              return w.whatsappId;
            })
          },
          status: status
        }
      });
    }
  } catch (err) {
    console.log(
      "There was an error on select a whatsapp id by user queue: ",
      err
    );
  }

  return defaultWhatsapp;
};

export default wbotByUserQueue;
