import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import NewPost from '../views/NewPost.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import SearchResults from '../views/SearchResults.vue'
import ArticleDetail from '../views/ArticleDetail.vue'
import Profile from '../views/Profile.vue'
import EditPost from '../views/EditPost.vue'
import { useAuthStore } from '../store/auth'
import { useToast } from '../composables/useToast'
import { setupAuthGuard } from './guards'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', name: 'Home', component: Home },
  { path: '/latest', name: 'Latest', component: Home },
  { path: '/hot', name: 'Hot', component: Home },
  {
    path: '/posts/new',
    name: 'NewPost',
    component: EditPost,
    meta: { requiresAuth: true }
  },
  {
    path: '/posts/:id/edit',
    name: 'EditPost',
    component: EditPost,
    meta: { requiresAuth: true }
  },
  { 
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { guestOnly: true }
  },
  { 
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { guestOnly: true }
  },
  { path: '/search-results', name: 'SearchResults', component: SearchResults },
  { path: '/article/:id', name: 'ArticleDetail', component: ArticleDetail },
  { 
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true }
  },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/ErrorPage.vue') }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const { showToast } = useToast()

  // 需要登录的路由
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    showToast('请先登录', 'warning')
    next('/login')
    return
  }

  // 已登录用户不能访问登录和注册页
  if (to.meta.guestOnly && authStore.isAuthenticated) {
    next('/')
    return
  }

  next()
})

// 设置认证守卫
setupAuthGuard(router)

export default router
