import type { Router } from 'vue-router'

import { storeToRefs } from 'pinia'

import pinia from '@/plugins/pinia/setup'
import { useAuthStore } from '@/stores/auth'

// 需要认证的路由前缀
const AUTH_ROUTES = ['/monisuo/', '/dashboard', '/users', '/tasks', '/settings']

export function authGuard(router: Router) {
  router.beforeEach((to, _from) => {
    const authStore = useAuthStore(pinia)
    const { isLogin } = storeToRefs(authStore)

    // 检查是否是需要认证的路由
    const needsAuth = to.meta.auth || AUTH_ROUTES.some(prefix => to.path.startsWith(prefix))

    // 如果页面需要登录但用户未登录，重定向到登录页并记录原始目标页面
    if (needsAuth && !unref(isLogin) && to.name !== '/auth/sign-in') {
      return {
        name: '/auth/sign-in',
        query: { redirect: to.fullPath },
      }
    }
  })
}
