import { useUserStore } from '@/stores';
import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/pages/login/login-page.vue'),
    },
    {
      path: '/',
      component: () => import('@/layouts/app-layout.vue'),
      redirect: '/station',
      children: [
        {
          path: 'station',
          component: () => import('@/pages/station/station-page.vue'),
        },
        {
          path: 'device',
          component: () => import('@/pages/device/device-page.vue'),
        },
        {
          path: 'alarm',
          children: [
            {
              path: 'alarm-log',
              component: () => import('@/pages/alarm/alarm-log-page.vue'),
            },
            {
              path: 'alarm-ignore',
              component: () => import('@/pages/alarm/alarm-ignore-page.vue'),
            },
          ],
        },
        {
          path: 'log',
          children: [
            {
              path: 'vimp-log',
              component: () => import('@/pages/log/vimp-log-page.vue'),
            },
            {
              path: 'call-log',
              component: () => import('@/pages/log/call-log-page.vue'),
            },
          ],
        },
        {
          path: 'permission',
          component: () => import('@/pages/permission/permission-page.vue'),
          beforeEnter: () => {
            const userStore = useUserStore();
            if (userStore.isLamp) return true;
            return { path: '/404' };
          },
        },
        {
          path: '/:pathMatch(.*)*',
          component: () => import('@/pages/error/not-found-page.vue'),
        },
      ],
    },
  ],
});

router.beforeEach((to) => {
  const whiteList: string[] = [];
  const inWhiteList = whiteList.some((path) => to.path.startsWith(path));
  if (inWhiteList) {
    return true;
  }

  const userStore = useUserStore();
  const isAuthed = !!userStore.userLoginResult?.token;

  if (to.path === '/login') {
    if (isAuthed) {
      return { path: '/' };
    } else {
      return true;
    }
  } else {
    if (!isAuthed) {
      return { path: '/login' };
    } else {
      return true;
    }
  }
});

export default router;
