import { createRouter, createWebHistory } from 'vue-router'
import NoteView from '@/views/NoteView.vue'
import { initAuth, handleCallback, login, authState } from '@/composables/useAuth'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'note',
            component: NoteView,
        },
        {
            path: '/auth/callback',
            name: 'callback',
            component: NoteView,
        },
    ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 处理回调路径
    if (to.path === '/auth/callback') {
        if (to.query.code) {
            try {
                await handleCallback()
                next({ path: '/', replace: true })
                return
            } catch (error) {
                console.error('[Router] Callback failed:', error)
            }
        }
    }

    // 初始化认证状态
    await initAuth()

    // 检查是否已认证
    if (!authState.isAuthenticated.value) {
        // 未登录，跳转到 Authentik 登录
        await login()
        return
    }

    // 已认证，继续访问
    next()
})

export default router
