import AppError from "../errors/AppError";
import Whatsapp from "../models/Whatsapp";

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

import { Op, where } from "sequelize";

import wbotByUserQueue from "../helpers/GetWbotByUserQueue";

import { WhatsIndex } from "./LoadBalanceWhatsSameQueue";

interface Request {
  userId?: string | number;
  queueId?: string | number;
  ignoreNoWhatsappFound?: boolean
}
 
const GetDefaultWhatsApp = async ({
  userId,
  queueId, 
  ignoreNoWhatsappFound = false
}: Request): Promise<any> => { 
  let defaultWhatsapp = await Whatsapp.findOne({
    where: { isDefault: true }
  });

  if (!defaultWhatsapp) { 
    if (userId) {
      let whatsapps = await wbotByUserQueue({ userId, queueId });

      if (userId && queueId) {
        if (whatsapps.length > 1) {
          let whatsAppOfficial: any = whatsapps.find(
            (w: any) => w.phoneNumberId && w.phoneNumberId.trim().length > 0
          );

          if (whatsAppOfficial) {
            return whatsapps;
          }
        }
      }

      if (whatsapps.length > 0) {
        if (whatsapps.length > 1) {
          defaultWhatsapp = whatsapps[+WhatsIndex(whatsapps)];
        } else {
          defaultWhatsapp = whatsapps[0];
        }
      } // Quando o usuário não está em nenhuma fila
      else {
        defaultWhatsapp = await Whatsapp.findOne({
          where: { status: "CONNECTED" }
        });
      }
    } else { 
      defaultWhatsapp = await Whatsapp.findOne({
        where: { status: "CONNECTED", isOfficial: false }
      });
    }
  }  
 
  if (!defaultWhatsapp && !ignoreNoWhatsappFound) { 
    throw new AppError("ERR_NO_DEF_WAPP_FOUND");
  }

  return defaultWhatsapp; 
};

export default GetDefaultWhatsApp;
