import AppError from "../../errors/AppError";
import { get, set } from "../../helpers/RedisClient";
import { updateTicketCacheByTicketId } from "../../helpers/TicketCache";
import { getIO } from "../../libs/socket";
import Message from "../../models/Message";
import Ticket from "../../models/Ticket";

interface MessageData {
  id: string;
  ticketId: number;
  body: string;
  contactId?: number;
  fromMe?: boolean;
  read?: boolean;
  mediaType?: string;
  mediaUrl?: string;
  fromAgent?: boolean;
}
interface Request {
  messageData: MessageData;
}

const CreateMessageService = async ({
  messageData
}: Request): Promise<Message> => {
  try {
    await Message.upsert(messageData);

    const message = await Message.findByPk(messageData.id, {
      include: [
        "contact",
        {
          model: Ticket,
          as: "ticket",
          include: ["contact", "queue"]
        },
        {
          model: Message,
          as: "quotedMsg",
          include: ["contact"]
        }
      ]
    });

    if (!message) {
      throw new Error("ERR_CREATING_MESSAGE");
    }

    //////////////////// SETTINGS ///////////////////////////
    let ticketRemote = await get({
      key: `remote:ticketId:${message.ticket.id}`
    });

    if (ticketRemote && !ticketRemote.includes("messageDateTime")) {
      ticketRemote = JSON.parse(ticketRemote);

      ticketRemote = {
        ...ticketRemote,
        ...{ messageDateTime: message.createdAt }
      };

      const ticket = await Ticket.findByPk(message.ticket.id);
      ticket?.update({ remoteDone: true });

      console.log('MESSAGE SERVICE: XXXXXXXXXXXXXXXXXXXXXXX')

      set(`remote:ticketId:${message.ticket.id}`, JSON.stringify(ticketRemote));
    }
    //////////////////////////////////////////////////////////

    if (message.ticket.status != "queueChoice") {
      await updateTicketCacheByTicketId(message.ticket.id, {
        lastMessage: message.body,
        updatedAt: new Date(message.ticket.updatedAt).toISOString(),
        "contact.profilePicUrl": message.ticket.contact.profilePicUrl,
        unreadMessages: message.ticket.unreadMessages
      });

      const io = getIO();
      io.to(message.ticketId.toString())
        .to(message.ticket.status)
        .to("notification")
        .emit("appMessage", {
          action: "create",
          message,
          ticket: message.ticket,
          contact: message.ticket.contact
        });
    }

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

export default CreateMessageService;
