
<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);
    }

  } 
  // variable

  // excute in setup
  
  //lifecycle
  
  //function
  const startRouteGuard = async (to:RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    const mainStore = useMainStore();
    const mainStoreRef = storeToRefs(mainStore);
    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>
