import { setTicketData, useTicketStore } from "@/stores/ticket";
import { useUserStore } from "@root/user";
import { enqueueSnackbar } from "notistack";
import { createTicket, sendTicketMessage } from "@frontend/kitui";
import { parseAxiosError } from "@/utils/parse-error";

interface SelectSendingMethod {
  messageField: string;
  isSnackbar?: boolean;
  systemError?: boolean;

}
export const selectSendingMethod = async ({ messageField, isSnackbar = true, systemError = false }: SelectSendingMethod) => {
  const user = useUserStore.getState().user?._id;
  const ticket = useTicketStore.getState()[user ? "authData" : "unauthData"];

  let successful = false;
  if (!(window.location.hostname == 'localhost' && systemError)) { //предупреждать о системных ошибках вне локалхост
    if (!ticket.sessionData?.ticketId) {
      const [data, createError] = await createTicket({
        message: messageField,
        useToken: Boolean(user),
        systemError: false,
      });

      if (createError || !data) {
        successful = false;

        if (isSnackbar) enqueueSnackbar(`Не удалось открыть диалог ${parseAxiosError(createError)}`);
      } else {
        successful = true;

        setTicketData({ ticketId: data.Ticket, sessionId: data.sess });
      }

    } else {
      const [_, sendTicketMessageError] = await sendTicketMessage({
        ticketId: ticket.sessionData?.ticketId,
        message: messageField,
        systemError: false,
      });
      successful = true;

      if (sendTicketMessageError) {
        successful = false;
        if (isSnackbar) enqueueSnackbar(sendTicketMessageError);
      }
    }
  }
  return successful;
}