import { Op } from "sequelize";
import AppError from "../errors/AppError";
import Ticket from "../models/Ticket";
import User from "../models/User";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
import { getSettingValue } from "./WhaticketSettings";
import ListWhatsAppsForQueueService from "../services/WhatsappService/ListWhatsAppsForQueueService";

const CheckContactOpenTickets = async (
  contactId: number,
  whatsappId: number | string,
  handle?: boolean
): Promise<void | any> => {
  let ticket;

  if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
    let whats = await ListWhatsAppsNumber(whatsappId);

    // console.log("contactId: ", contactId, " | whatsappId: ", whatsappId);

    // console.log("WHATS: ", JSON.stringify(whats, null, 6));

    ticket = await Ticket.findOne({
      where: {
        [Op.and]: [
          { contactId: contactId },
          { whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) } },
          { status: { [Op.or]: ["open", "pending"] } }
        ]
      }
    });

    console.log("TICKET: ", JSON.stringify(ticket, null, 6));
  } else {
    ticket = await Ticket.findOne({
      where: { contactId, status: { [Op.or]: ["open", "pending"] } }
    });
  }

  if (ticket) {
    if (handle) return true;
    const userName = await User.findOne({
      where:{ id: ticket.userId }
     });
    const error = new AppError("ERR_OTHER_OPEN_TICKET");
    error.message = `Erro: já existe um ticket criado com esse contato. Responsável: ${userName? userName.name.toUpperCase() : 'Aguardando'}`;
     
    throw error;
  }

  
};

export default CheckContactOpenTickets;
