import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import MainView from '@/views/MainView.vue'
import MainViewExample from '@/views/MainViewExample.vue'
import userInfo from '@/components/userInfo'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { isRequiredAuth: false },
    },
    {
      path: '/about.html',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
      meta: { isRequiredAuth: false },
    },
    {
      path: '/login.html',
      name: 'login',
      component: LoginView,
      meta: { isRequiredAuth: false },
    },
    {
      path: '/main.html',
      name: 'main',
      component: MainView,
      meta: { isRequiredAuth: true },
    },
    {
      path: '/main-example.html',
      name: 'main-example',
      component: MainViewExample,
      meta: { isRequiredAuth: false },
    },
  ],
})
console.log('test')

router.beforeEach((to, from, next) => {
  if (to.meta.isRequiredAuth && !userInfo.isLogin) {
    next('/login.html')
  } else if ((to.path === '/login.html' || to.path === '/') && userInfo.isLogin) {
    next('/main.html')
  } else {
    next()
  }
})

export default router
