import { Sequelize } from "sequelize";
import Whatsapp from "../../models/Whatsapp";
import WhatsappQueue from "../../models/WhatsappQueue";
const dbConfig = require("../../config/database");
const { QueryTypes } = require("sequelize");

const sequelize = new Sequelize(dbConfig);

const ListWhatsAppsForQueueService = async (
  queueId: number | string,
  status?: string
): Promise<any> => {
  let distinctWhatsapps: any[] = [];

  if (status) {
    distinctWhatsapps = await sequelize.query(
      `SELECT w.id, w.number, w.status, wq.whatsappId, wq.queueId FROM Whatsapps w
     JOIN WhatsappQueues wq ON w.id = wq.whatsappId AND wq.queueId = ${queueId} AND w.status = '${status}' 
     AND phoneNumberId = false 
     GROUP BY w.number;`,
      { type: QueryTypes.SELECT }
    );
  } else {
    distinctWhatsapps = await sequelize.query(
      `SELECT w.id, w.number, w.status, wq.whatsappId, wq.queueId FROM Whatsapps w
     JOIN WhatsappQueues wq ON w.id = wq.whatsappId AND wq.queueId = ${queueId}
     GROUP BY w.number;`,
      { type: QueryTypes.SELECT }
    );
  }

  return distinctWhatsapps;
};

export default ListWhatsAppsForQueueService;
