import { Request, Response } from "express";
import { getIO } from "../libs/socket";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { logger } from "../utils/logger";
import * as Sentry from "@sentry/node";
import Whatsapp from "../models/Whatsapp";
import omnihitDashboardSession from "../helpers/OmnhitDashboardSession";

// type IndexQuery = {
//   centro_custo: string;
// };

export const wbotMonitorRemote = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const { action, whatsappId, reason } = req.body;

  console.log(
    "action: ",
    action,
    " | whatsappId: ",
    whatsappId,
    " | reason: ",
    reason
  );

  console.log("-----------> ACTION: ", req.body["action"]);

  const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true });

  if (whatsapp) {
    if (action === "disconnected") {
      logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`);
    }

    let data: any = {};
    data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME };
    data.action = "update";
    await omnihitDashboardSession(data);

    const io = getIO();
    io.emit("whatsappSession", {
      action: "update",
      session: whatsapp
    });
  }

  return res.status(200).json({ message: "Ok" });
};

export const wbotMonitorQrcodeRemote = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const { whatsappId } = req.body;

  console.log(
    "-----------> QRCODE MONITOR whatsappId: ",
    req.body["whatsappId"]
  );

  const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true });
  // let whatsapp = await ShowWhatsAppService(whatsappId)

  if (whatsapp) {
    let data: any = {};
    data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME };
    data.action = "update";
    await omnihitDashboardSession(data);
  }

  if (whatsapp) {
    const io = getIO();
    io.emit("whatsappSession", {
      action: "update",
      session: whatsapp
    });
  }

  return res.status(200).json({ message: "Ok" });
};

export const wbotMonitorQrcodeNumberRead = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const { number } = req.body;

  console.log("-----------> number read: ", number);

  const msg = `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`;
  let data: any = {};
  data.msg = msg;
  data.action = "error";
  await omnihitDashboardSession(data);

  const io = getIO();
  io.emit("whatsappSession", {
    action: "error",
    msg: `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`
  });

  return res.status(200).json({ message: "Ok" });
};
