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

const sequelize = new Sequelize(dbConfig);

const ListWhatsappQueueByUserQueue = async (
  userId: number | string,
  profiles: string
): Promise<any> => {
  const users = await sequelize.query(
    `select wq.whatsappId, wq.queueId, uq.userId, uq.queueId, u.id, u.name, u.profile, w.number
from WhatsappQueues wq join UserQueues uq join Users u join Whatsapps w on
wq.queueId = uq.queueId where u.id = uq.userId and u.profile in (${profiles}) and u.id = ${userId} 
and w.id = wq.whatsappId group by w.number ;`,
    { type: QueryTypes.SELECT }
  );

  return users;
};

const ListWhatsappQueesByUser = async (whatsappIds: string): Promise<any> => {
  const users = await sequelize.query(
    `SELECT
    wq.whatsappId, wq.queueId, q.name, q.id, q.name, q.color 
FROM
    WhatsappQueues wq
JOIN
    Queues q ON wq.whatsappId IN (${whatsappIds})  AND q.id = wq.queueId group by wq.queueId;

`,
    { type: QueryTypes.SELECT }
  );

  return users;
};

const ListUserByWhatsappQueuesService = async (
  userId: number | string,
  profiles: string
): Promise<any> => {
  const whatsapps: any = await ListWhatsappQueueByUserQueue(userId, profiles);

  let whatsappIds = whatsapps.map((w: any) => w.whatsappId);

  if (whatsappIds.length == 0) return { users: [], queues: [] };

  console.log("----------> whatsappIds: ", whatsappIds, " | userId: ", userId);

  whatsappIds = whatsappIds.join(", ");

  const users: any = await sequelize.query(
    `select wq.whatsappId, wq.queueId, uq.userId, uq.queueId, u.id, u.name, u.profile
from WhatsappQueues wq join UserQueues uq join Users u on
wq.queueId = uq.queueId where u.id = uq.userId and u.profile in (${profiles}) and wq.whatsappId in (${whatsappIds}) group by u.id;`,
    { type: QueryTypes.SELECT }
  );

  const queues = await ListWhatsappQueesByUser(whatsappIds);

  return { users, queues };
};

export default ListUserByWhatsappQueuesService;
