import * as Yup from "yup";

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

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

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

const CreateWhatsAppService = async ({
  name,
  url,
  urlApi,
  status = "OPENING",
  queueIds = [],
  greetingMessage,
  farewellMessage,
  isDefault = false,
  isOfficial = false,
  phoneNumberId,
  wabaId,
  number
}: Request): Promise<Response> => {
  try {
    const schema = Yup.object().shape({
      name: Yup.string()
        .required()
        .min(2)
        .test(
          "Check-name",
          "This whatsapp name is already used.",
          async value => {
            if (!value) return false;
            const nameExists = await Whatsapp.findOne({
              where: { name: value }
            });
            return !nameExists;
          }
        ),
      isDefault: Yup.boolean().required()
    });

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

    const whatsappFound = await Whatsapp.findOne();

    isDefault = !whatsappFound;

    let oldDefaultWhatsapp: Whatsapp | null = null;

    if (isDefault) {
      oldDefaultWhatsapp = await Whatsapp.findOne({
        where: { isDefault: true }
      });
      if (oldDefaultWhatsapp) {
        await oldDefaultWhatsapp.update({ isDefault: false });
      }
    }

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

    const classification = isOfficial ? "GREEN" : null;

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

    const whatsapp = await Whatsapp.create(
      {
        name,
        status,
        url,
        urlApi,
        greetingMessage,
        farewellMessage,
        isDefault,
        phoneNumberId,
        wabaId,
        isOfficial,
        number,
        classification
      },
      { include: ["queues"] }
    );

    await AssociateWhatsappQueue(whatsapp, queueIds);

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

export default CreateWhatsAppService;
