import AppError from "../../errors/AppError";
import CheckContactOpenTickets from "../../helpers/CheckContactOpenTickets";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket";
import ShowContactService from "../ContactServices/ShowContactService";

import { getIO } from "../../libs/socket";
import ShowUserServiceReport from "../UserServices/ShowUserServiceReport";

import format from "date-fns/format";
import ptBR from "date-fns/locale/pt-BR";
import { splitDateTime } from "../../helpers/SplitDateTime";
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";

import { createOrUpdateTicketCache } from "../../helpers/TicketCache";
import User from "../../models/User";
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
import Whatsapp from "../../models/Whatsapp";
import ListWhatsAppsForQueueService from "../WhatsappService/ListWhatsAppsForQueueService";
import { json } from "sequelize";
let flatten = require("flat");

interface Request {
  contactId: number;
  status: string;
  userId: number;
  queueId?: number | undefined;
  whatsappId?: number | string;
}

const CreateTicketService = async ({
  contactId,
  status,
  userId,
  queueId = undefined,
  whatsappId
}: Request): Promise<Ticket> => {
  try {
    let defaultWhatsapp;

    if (whatsappId) {
      defaultWhatsapp = await Whatsapp.findByPk(whatsappId);
    } else {
      defaultWhatsapp = await GetDefaultWhatsApp({ userId, queueId });
    }

    // if (queueId) {
    //   const whatsappsByQueue = await ListWhatsAppsForQueueService(queueId);

    //   const exist = await CheckContactOpenTickets(
    //     contactId,
    //     defaultWhatsapp.id,
    //     true
    //   );

    //   console.log(
    //     "whatsappsByQueue: ",
    //     JSON.stringify(whatsappsByQueue, null, 6)
    //   );

    //   if (exist) {
    //     console.log("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
    //   }

    //   return new Ticket();
    // }

    // console.log(JSON.stringify(defaultWhatsapp, null, 2));
    // throw new AppError("test error");

    const { phoneNumberId } = defaultWhatsapp;

    const user = await User.findByPk(userId, { raw: true });

    if (!queueId) {
      const matchingQueue = await whatsappQueueMatchingUserQueue(
        userId,
        defaultWhatsapp,
        user?.profile
      );

      queueId = matchingQueue ? matchingQueue.queueId : undefined;
    }

    console.log(
      "xxxxxxxxxxxx contactId: ",
      contactId,
      " | defaultWhatsapp.id: ",
      defaultWhatsapp.id
    );

    await CheckContactOpenTickets(contactId, defaultWhatsapp.id);

    const { isGroup } = await ShowContactService(contactId);

    const { id }: Ticket = await defaultWhatsapp.$create("ticket", {
      contactId,
      status,
      isGroup,
      userId,
      queueId,
      phoneNumberId
    });

    const ticket = await Ticket.findByPk(id, { include: ["contact"] });

    if (!ticket) {
      throw new AppError("ERR_CREATING_TICKET");
    }

    // console.log('CONTACT ticket.id: ', ticket.id)

    // TEST DEL
    try {
      let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
      let ticket_obj = JSON.parse(jsonString); //to make plain json
      delete ticket_obj["contact"]["extraInfo"];

      ticket_obj = flatten(ticket_obj);

      await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
    } catch (error) {
      console.log(
        "There was an error on UpdateTicketService.ts on createTicketCache from user: ",
        error
      );
    }
    //

    const dateToday = splitDateTime(
      new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
    );

    TicketEmiterSumOpenClosedByUser(
      userId.toString(),
      dateToday.fullDate,
      dateToday.fullDate
    );

    const io = getIO();
    io.emit("ticketStatus", {
      action: "update",
      ticketStatus: { ticketId: ticket.id, status: ticket.status }
    });

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

export default CreateTicketService;
