import {useChatsStore} from "~/stores/useChats";


export default defineNuxtRouteMiddleware((to, from) => {
  if (import.meta.server) return;

  const authStore = useAuthStore();
  const { token } = storeToRefs(authStore);
  const userInfoStore = useUserInfoStore();
  const {userInfo} = storeToRefs(userInfoStore);

  const chatsStore = useChatsStore()

  if (token.value) {
    const config = useRuntimeConfig()
    const baseIM = config.public.baseIM
    // 俏的
/*
    const chatStore = useChatStore()
    chatStore.createConnection(baseIM + '?token=' + userInfo.value.pass)
*/

     userInfoStore.getUserInfo().then(() => {
      // chatsStore.initWebSocket(baseIM + '?token=' + userInfo.value.pass)
      chatsStore.initWebSocket(baseIM + '?token=' + userInfo.value.pass)
    })
    return
  }

  if (to.fullPath.includes("/profile")) {
    return navigateTo("/login", {
      replace: true,
      query: {
        redirect: to.fullPath,
      },
    });
  }

  if (to.fullPath.includes("/note-create")) {
    return navigateTo("/login", {
      replace: true,
      query: {
        redirect: to.fullPath,
      },
    });
  }
  return;
});
