import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/store/authStore'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/Home.vue'),
      meta: { title: '首页', requiresAuth: true }
    },
    {
      path: '/search',
      name: 'DataImport',
      component: () => import('@/views/DataImport.vue'),
      meta: { title: '数据入库', requiresAuth: true }
    },
    {
      path: '/demand',
      name: 'DataSearch',
      component: () => import('@/views/DataSearch.vue'),
      meta: { title: '数据检索', requiresAuth: true }
    },
    {
      path: '/input/:id?',
      name: 'DataInput',
      component: () => import('@/views/TaskData.vue'),
      meta: { title: '数据信息录入', requiresAuth: true }
    },
    {
      path: '/statistics',
      name: 'Statistics',
      component: () => import('@/views/Statistics.vue'),
      meta: { title: '统计分析', requiresAuth: true }
    },
    {
      path: '/contact',
      name: 'Contact',
      component: () => import('@/views/Contact.vue'),
      meta: { title: '联系我们', requiresAuth: true }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录', requiresAuth: false }
    }
  ]
})

router.beforeEach((to, _from, next) => {
  if (to.meta.title) {
    document.title = '深海地球物理数据管理可视化平台 - ' + to.meta.title
  }

  const authStore = useAuthStore()

  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (to.path === '/login' && authStore.isLoggedIn) {
    next('/')
  } else {
    next()
  }
})

export default router
