import * as Yup from "yup";
import { Op } from "sequelize";

import AppError from "../../errors/AppError";
import Whatsapp from "../../models/Whatsapp";
import ShowWhatsAppService from "./ShowWhatsAppService";
import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getWbot } from "../../libs/wbot";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";

interface WhatsappData {
  name?: string;
  url?: string;
  urlApi?: string;
  status?: string;
  session?: string;
  isDefault?: boolean;
  isOfficial?: boolean;
  phoneNumberId?: string;
  wabaId?: string;
  greetingMessage?: string;
  farewellMessage?: string;
  queueIds?: number[];
  number?:string;
}

interface Request {
  whatsappData: WhatsappData;
  whatsappId: string;
}

interface Response {
  whatsapp: Whatsapp;
  oldDefaultWhatsapp: Whatsapp | null;
}

const UpdateWhatsAppService = async ({
  whatsappData,
  whatsappId
}: Request): Promise<Response> => {
  try {
    const schema = Yup.object().shape({
      name: Yup.string().min(2),
      status: Yup.string(),
      isDefault: Yup.boolean()
    });

    let {
      name,
      status,
      isDefault,
      phoneNumberId,
      wabaId,
      isOfficial,
      number,
      url,
      urlApi,
      session,
      greetingMessage,
      farewellMessage,
      queueIds = []
    } = whatsappData;

    try {
      await schema.validate({ name, status, isDefault });
    } catch (err: any) {
      throw new AppError(err.message);
    }

    if (queueIds.length > 1 && !greetingMessage) {
      throw new AppError("ERR_WAPP_GREETING_REQUIRED");
    }

    let oldDefaultWhatsapp: Whatsapp | null = null;

    if (isDefault) {
      oldDefaultWhatsapp = await Whatsapp.findOne({
        where: { isDefault: true, id: { [Op.not]: whatsappId } }
      });
      if (oldDefaultWhatsapp) {
        await oldDefaultWhatsapp.update({ isDefault: false });
      }
    }

    const whatsapp = await ShowWhatsAppService(whatsappId);

    // console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp)))

    if (
      name &&
      !name.includes(whatsapp.number) &&
      whatsapp.status === "CONNECTED" &&
      !whatsapp.isOfficial
    ) {
      throw new AppError("ERR_WAPP_WRONG_SESSION_NAME");
    }

    const classification = isOfficial ? "GREEN" : null;

    if (isOfficial) {
      status = "CONNECTED";
    }

    if (whatsapp.isOfficial && !isOfficial) {
      status = "OPENING";
    }

    await whatsapp.update({
      name,
      status,
      session,
      url,
      urlApi,
      greetingMessage,
      farewellMessage,
      isDefault,
      isOfficial,
      phoneNumberId,
      wabaId,
      number,
      classification
    });

    // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
    //   name,
    //   status,
    //   session,
    //   greetingMessage,
    //   farewellMessage,
    //   isDefault
    // })

    await AssociateWhatsappQueue(whatsapp, queueIds);

    return { whatsapp, oldDefaultWhatsapp };
  } catch (error: any) {
    console.error("===> Error on UpdateWhatsAppService.ts file: \n", error);
    throw new AppError(error.message);
  }
};

export default UpdateWhatsAppService;
