import { defineStore } from "pinia";
import { Notify } from "quasar";

import { io, Socket } from "socket.io-client";

import config from "@/app.config";
import { getToken } from "@/plugins/auth";

interface sockeBackup {
  message: string;
  success: boolean;
}

export const useSocketStore = defineStore("socket", () => {
  let socket: Socket;

  async function init() {
    socket = io(new URL(config.API.socket).origin, {
      auth: { token: await getToken() },
      path: "/api/v1/backup-socket",
    });
    socket.on("backup-notification", (payload) => {
      let body: sockeBackup = JSON.parse(payload);
      notifyStatus(body.message, body.success);
    });
  }

  function notifyStatus(message: string, success: boolean) {
    Notify.create({
      group: false,
      type: success ? "positive" : "negative",
      message: `${message}`,
      position: "top",
      timeout: 0,
      actions: [
        {
          icon: "close",
          color: "white",
          round: true,
        },
      ],
    });
  }

  init();

  return {};
});
