import path from "path";
import { getIO } from "../libs/socket";
import Message from "../models/Message";
import Ticket from "../models/Ticket";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { logger } from "../utils/logger";
import GetTicketWbot from "./GetTicketWbot";
import fs from 'fs';
import { restartWhatsSession } from "./RestartWhatsSession";
import { Session } from "@sentry/types";
import { splitDateTime } from "./SplitDateTime";

import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";

const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
  await Message.update(
    { read: true },
    {
      where: {
        ticketId: ticket.id,
        read: false
      }
    }
  );

  await ticket.update({ unreadMessages: 0 });

  try {

    const wbot = await GetTicketWbot(ticket);

    // test del
    // throw new Error('Throw makes it go boom!')
    //

    await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);

  } catch (err) {

    logger.warn(`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`); 

    //Solução para contornar erro de sessão
    if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {

      const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`)

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

      const whatsapp = await ShowWhatsAppService(ticket.whatsappId);

      if (whatsapp && whatsapp.status == 'CONNECTED') {

        let timestamp = Math.floor(Date.now() / 1000)

        fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error) => { });

        // await restartWhatsSession(whatsapp)

      }

    }
  }

  const io = getIO();
  io.to(ticket.status).to("notification").emit("ticket", {
    action: "updateUnread",
    ticketId: ticket.id
  });
};

export default SetTicketMessagesAsRead;
