<template>
  <router-view></router-view>
</template>

<script lang="ts">
import { onBeforeRouteUpdate } from "vue-router";
import type { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { useMainStore } from "@/stores/main";
import { storeToRefs } from "pinia";
export default {
  setup() {
    onBeforeRouteUpdate((to, from, next) => {
      startRouteGuard(to, from, next);
    });
  },
  beforeRouteEnter(to, from, next) {
    startRouteGuard(to, from, next);
  },
};

//function
const startRouteGuard = async (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) => {
  const mainStore = useMainStore();
  const mainStoreRef = storeToRefs(mainStore);

  if (to.path === "/qrcode" || to.path === "/yt-views") {
    next();
    mainStore.qrCheckLoggedIn();
  } else {
    mainStore.checkLoggedIn();
  }

  if (mainStoreRef.readIsLoggedIn.value) {
    if (to.path === "/login" || to.path === "/") {
      next("/main/dashboard");
    } else {
      next();
    }
  } else if (mainStoreRef.readIsLoggedIn.value === false) {
    if (to.path === "/" || (to.path as string).startsWith("/main")) {
      next("/login");
    } else {
      next();
    }
  }
};
</script>
