import { createRouter, createWebHistory } from 'vue-router'
import { checkAuth } from '@/api'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { public: true, guestOnly: true },
  },
  {
    path: '/',
    component: () => import('@/components/MainLayout.vue'),
    children: [
      { path: '', redirect: '/machines' },
      {
        path: 'machines',
        name: 'MachineList',
        component: () => import('@/views/MachineList.vue'),
        meta: { public: true },
      },
      {
        path: 'machines/:id',
        name: 'MachineDetail',
        component: () => import('@/views/MachineDetail.vue'),
        meta: { public: true },
      },
      {
        path: 'topology',
        name: 'Topology',
        component: () => import('@/views/Topology.vue'),
        meta: { admin: true },
      },
      {
        path: 'logs',
        name: 'Logs',
        component: () => import('@/views/Logs.vue'),
        meta: { admin: true },
      },
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

let authChecked = false
let authState = { is_admin: false }

router.beforeEach(async (to, from, next) => {
  if (!authChecked) {
    try {
      const { data } = await checkAuth()
      authState = data
    } catch (e) {
      authState = { is_admin: false }
    }
    authChecked = true
  }

  // 访客禁止进入机器详情页
  if (to.name === 'MachineDetail' && !authState.is_admin) {
    return next('/machines')
  }

  if (to.meta.admin && !authState.is_admin) {
    return next('/login?redirect=' + encodeURIComponent(to.fullPath))
  }
  if (to.meta.guestOnly && authState.is_admin) {
    return next('/')
  }
  next()
})

export function refreshAuth() {
  authChecked = false
}

export function setAuth(data) {
  authState = data
}

export function getAuth() {
  return authState
}

export default router
