import { getIO } from "../../libs/socket";
import Contact from "../../models/Contact";

import { createOrUpdateContactCache } from '../../helpers/ContactsCache'
import { tr } from "date-fns/locale";
import AppError from "../../errors/AppError";

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

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

const CreateOrUpdateContactService = async ({
  name,
  number: rawNumber,
  profilePicUrl,
  isGroup,
  email = "",
  extraInfo = []
}: Request): Promise<Contact> => {

  try {

    const number = isGroup ? rawNumber : rawNumber.replace(/[^0-9]/g, "");

    const io = getIO();
    let contact: Contact | null;


    contact = await Contact.findOne({ where: { number } });

    if (contact) {
      contact.update({ profilePicUrl });

      // TEST DEL
      await createOrUpdateContactCache(`contact:${contact.id}`, { profilePicUrl })
      //

      io.emit("contact", {
        action: "update",
        contact
      });
    } else {
      contact = await Contact.create({
        name,
        number,
        profilePicUrl,
        email,
        isGroup,
        extraInfo
      });

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


      io.emit("contact", {
        action: "create",
        contact
      });
    }

    return contact;

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

};

export default CreateOrUpdateContactService;
