import { Ticket, UserAccount, UserName, getAuthToken, useSSESubscription } from "@frontend/kitui"
import { useUserStore } from "@root/user";
import { useSSETab } from "./useSSETab";
import { cancelPayCartProcess } from "@/stores/notEnoughMoneyAmount";
import { setCash } from "@/stores/cash";
import { currencyFormatter } from "@/pages/Tariffs/tariffsUtils/currencyFormatter";
import { inCart } from "@/pages/Tariffs/utils";

type Ping = [{ event: "ping" }]

type SomeChange = [{
  "id": UserAccount["_id"],
  "userId": UserAccount["userId"],
  "cart": UserAccount["cart"],
  "wallet": {
    "cash": UserAccount["wallet"]["cash"],
    "currency": UserAccount["wallet"]["currency"],
    "spent": UserAccount["wallet"]["spent"],
    "purchasesAmount": UserAccount["wallet"]["purchasesAmount"],
    "money": UserAccount["wallet"]["money"],
    "lastPaymentId": string;
  },
  "name": UserName,
  "status": UserAccount["status"],
  "isDeleted": UserAccount["isDeleted"],
  "createdAt": UserAccount["createdAt"];
  "updatedAt": UserAccount["updatedAt"];
  "from": string;
  "partner": string;
}]

type PipeMessage = Ping | SomeChange

export const usePipeSubscriber = () => {
  const token = getAuthToken();
  const userId = useUserStore((state) => state.userId);
  const { isActiveSSETab, updateSSEValue } = useSSETab<Ticket[]>("pipe");

  useSSESubscription({
    enabled: Boolean(token) && Boolean(userId) && isActiveSSETab,
    url:
      process.env.REACT_APP_DOMAIN +
      `/customer/v1.0.1/account/pipe?Authorization=${token}`,
    onNewData: (data) => {
      let message = data[0] as PipeMessage
      updateSSEValue(message)

      //Пропускаем пингование
      if ('event' in message && message.event === "ping") return


      if ('cart' in message) {
        //корзина была изменена, мы больше не хотим покупать
        cancelPayCartProcess()
        inCart()
      }
      else if ('wallet' in message) {
        setCash(
          currencyFormatter.format(Number(message.wallet) / 100),
          Number(message.wallet),
          Number(message.wallet) / 100,
        );
      }
    },
    marker: "pipe",
  });
}