import { Request, Response } from "express";

import { getIO } from "../libs/socket";
import AppError from "../errors/AppError";

import UpdateSettingService from "../services/SettingServices/UpdateSettingService";
import ListSettingsService from "../services/SettingServices/ListSettingsService";
import loadSettings from "../helpers/LoadSettings";
import updateSettingTicket from "../services/SettingServices/UpdateSettingTicket";
import SettingTicket from "../models/SettingTicket";
import Whatsapp from "../models/Whatsapp";
import whatsappOfficialNumberInfo from "../helpers/WhatsappOfficialNumberInfo";

export const index = async (req: Request, res: Response): Promise<Response> => {
  // if (req.user.profile !== "master") {
  //   throw new AppError("ERR_NO_PERMISSION", 403);
  // }

  const settings = await ListSettingsService();  

  return res.status(200).json({ settings });
};

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

  const config = await SettingTicket.findAll({ where: { number } });

  return res.status(200).json({ config });
};

export const updateTicketSettings = async (
  req: Request,
  res: Response
): Promise<Response> => {
  const {
    number,
    saturdayBusinessTime,
    outBusinessHours,
    ticketExpiration,
    weekend,
    saturday,
    sunday,
    holiday
  } = req.body;

  if (!number) throw new AppError("No number selected", 400);

  if (outBusinessHours && Object.keys(outBusinessHours).length > 0) {
    await updateSettingTicket({
      ...outBusinessHours,
      key: "outBusinessHours",
      number
    });
  }

  if (saturdayBusinessTime && Object.keys(saturdayBusinessTime).length > 0) {
    await updateSettingTicket({
      ...saturdayBusinessTime,
      key: "saturdayBusinessTime",
      number
    });
  }

  if (ticketExpiration && Object.keys(ticketExpiration).length > 0) {
    await updateSettingTicket({
      ...ticketExpiration,
      key: "ticketExpiration",
      number
    });
  }

  if (weekend && Object.keys(weekend).length > 0) {
    await updateSettingTicket({
      ...weekend,
      key: "weekend",
      number
    });
  }

  if (saturday && Object.keys(saturday).length > 0) {
    await updateSettingTicket({
      ...saturday,
      key: "saturday",
      number
    });
  }

  if (sunday && Object.keys(sunday).length > 0) {
    await updateSettingTicket({
      ...sunday,
      key: "sunday",
      number
    });
  }

  if (holiday && Object.keys(holiday).length > 0) {
    await updateSettingTicket({
      ...holiday,
      key: "holiday",
      number
    });
  }

  return res.status(200).json({
    outBusinessHours,
    ticketExpiration,
    weekend,
    saturday,
    sunday,
    holiday
  });
};

export const update = async (
  req: Request,
  res: Response
): Promise<Response> => {
  if (req.user.profile !== "master") {
    throw new AppError("ERR_NO_PERMISSION", 403);
  }
  const { settingKey: key } = req.params;
  const { value, obj } = req.body;

  const setting = await UpdateSettingService({
    key,
    value,
    obj
  });

  if (key && key == "whatsaAppCloudApi") {
    let whatsapps: any = await Whatsapp.findAll();

    if (whatsapps) {
      for (let i in whatsapps) {
        const { id, wabaId, isOfficial } = whatsapps[i];

        if (isOfficial && wabaId) {
          try {
            const whatsapp = await Whatsapp.findByPk(id);
            if (whatsapp) {
              if (value == "disabled") {
                whatsapp.update({ status: "OPENING" });
              } else if (value == "enabled") {
                const info = await whatsappOfficialNumberInfo(wabaId);
                if (info) {
                  whatsapp.update({
                    classification: info.quality_rating,
                    status: "CONNECTED"
                  });
                }
              }
            }
          } catch (error) {
            console.log(
              "error on try update classification number from oficial whatsapp in SettingControllers.ts: ",
              error
            );
          }
        }
      }
    }
  }

  loadSettings();
 
  const io = getIO();
  io.emit("settings", {
    action: "update",
    setting
  });

  return res.status(200).json(setting);
};
