import { Op, Sequelize } from "sequelize";
import Whatsapp from "../../models/Whatsapp";
import WhatsappQueue from "../../models/WhatsappQueue";
import { List } from "whatsapp-web.js";
import UserQueue from "../../models/UserQueue";
import Queue from "../../models/Queue";
const dbConfig = require("../../config/database");
const { QueryTypes } = require("sequelize");

const sequelize = new Sequelize(dbConfig);

const ListWhatsappQueuesByUserQueue = async (userId: string | number) => {
  try {
    let userQueue: any = await UserQueue.findAll({
      where: { userId },
      attributes: ["queueId"],
      raw: true
    });

    if (userQueue && userQueue.length > 0) {
      userQueue = userQueue.map((u: any) => u.queueId);

      const result = await sequelize.query(
        `select w.id, w.number, wq.whatsappId, wq.queueId, q.id, q.name from WhatsappQueues wq join Queues q on
wq.queueId = q.id join Whatsapps w
on wq.whatsappId = w.id where q.id in (${userQueue.join()})`,
        { type: QueryTypes.SELECT }
      );
      return result;
    }
  } catch (error) {
    console.error("Error fetching joined data:", error);
  }
  return [];
};

export default ListWhatsappQueuesByUserQueue;
