import type { Router } from 'vue-router'
import { useAuthStore } from '../store'

export function setupRouterGuard(router: Router) {
  const authStore = useAuthStore()
  authStore.restore()

  router.beforeEach((to, from, next) => {
    const isLoginPage = to.path === '/login'
    const isAuthenticated = !!authStore.token

    if (!isAuthenticated && !isLoginPage) {
      return next({ path: '/login', query: { redirect: to.fullPath } })
    }
    if (isAuthenticated && isLoginPage) {
      return next('/')
    }
    next()
  })
}
