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: '/demand',
      name: 'TaskDemand',
      component: () => import('@/views/TaskDemand.vue'),
      meta: { title: '任务需求', requiresAuth: true }
    },
    {
      path: '/search',
      name: 'TaskSearch',
      component: () => import('@/views/TaskSearch.vue'),
      meta: { title: '任务检索', requiresAuth: true }
    },
    {
      path: '/input/:id?',
      name: 'TaskInput',
      component: () => import('@/views/TaskInput.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
