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

import { createOrUpdateContactCache } from "../../helpers/ContactsCache";
import GetProfilePicUrl from "../WbotServices/GetProfilePicUrl";
import AssociateContatctQueue from "./AssociateContatctQueue";

interface ExtraInfo {
  name: string;
  value: string;
}

interface Request {
  name: string;
  number: string;
  email?: string;
  profilePicUrl?: string;
  extraInfo?: ExtraInfo[];
  queueIds?: number[];
}

const CreateContactService = async ({
  name,
  number,
  email = "",
  profilePicUrl = "",
  extraInfo = [],
  queueIds = []
}: Request): Promise<Contact> => {
  try {
    const numberExists = await Contact.findOne({
      where: { number }
    });

    if (numberExists) {
      throw new AppError("ERR_DUPLICATED_CONTACT");
    }

    const contact = await Contact.create(
      {
        name,
        number,
        email,
        profilePicUrl,
        extraInfo
      },
      {
        include: ["extraInfo"]
      }
    );

    await AssociateContatctQueue(contact, queueIds);

    // TEST DEL
    await createOrUpdateContactCache(`contact:${contact.id}`, {
      id: contact.id,
      name,
      number,
      profilePicUrl,
      isGroup: "false",
      extraInfo,
      email
    });
    //

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

export default CreateContactService;
