import { Op, Sequelize } from "sequelize";
import Queue from "../../models/Queue";
import User from "../../models/User";
import UserQueue from "../../models/UserQueue";
import { List } from "whatsapp-web.js";

interface Request {
  userId?: string | number;
  profile?: string;
  profiles?: Array<string>;
  raw?: boolean;
  userIds?: string | number;
  userQueues?: string[];
}

const ListUser = async ({
  profile,
  userId,
  raw,
  userIds,
  profiles,
  userQueues: userQueuesToNumber
}: Request): Promise<User[]> => {
  let where_clause = {};
  let userIdInQueues: number[] = [];
  
  if(userQueuesToNumber !== undefined){
    let userQueues = userQueuesToNumber.map(id => parseInt(id));
    const userQueuesFiltered = await UserQueue.findAll({
      where: { queueId: { [Op.or]: [userQueues, null] } },
      order: [
        ['userId', 'ASC']
      ],
      raw: true
    });
    if(userQueuesFiltered) for(let queueId of userQueues){
      for(let userQueue of userQueuesFiltered){
        if(queueId == userQueue.queueId){
          const isAlready = userIdInQueues.indexOf(userQueue.userId);

          if(isAlready === -1) userIdInQueues.push(userQueue.userId);
        }
      }
    }
  }
  if (userId && profile) {
    where_clause = {
      [Op.and]: [{ userId: userId }, { profile: profile }]
    };
  } else if (userId) {
    where_clause = {
      [Op.and]: [{ userId: userId }]
    };
  } else if (profile) {
    where_clause = {
      profile: profile
    };
  } else if (userIds) {
    where_clause = {
      id: { [Op.in]: userIds }
    };
  }
  else if (profiles && userIdInQueues.length > 0) {
    where_clause = {
      profile: { [Op.in]: profiles },
      id: {[Op.in]: userIdInQueues}
    };
  }
  else if (profiles) {
    where_clause = {
      profile: { [Op.in]: profiles }, 
    };
  }

  const users = await User.findAll({
    where: where_clause,
    raw,
    attributes: ["id", "name", "email", "transferToOtherQueues"],

    include: [
      { model: Queue, as: "queues", attributes: ["id", "name", "color"] }
    ],

    order: [["id", "ASC"]],
    group: userIds ? undefined : ["User.id"]
  });

  return users;
};

export default ListUser;
