import { fetchMy } from '@/api'
import type { Router } from 'vue-router'
import { useUserStore, useUserMemberStore } from '@/store'
import { useBasicLayout } from '@/hooks/useBasicLayout'

export function setupPageGuard(router: Router) {
    router.beforeEach(async (to, from, next) => {
        const { isMobile } = useBasicLayout()
        const userStore = useUserStore()
        const userMemberStore = useUserMemberStore()
        if (!userStore.userInfo.id) {
            try {
                await userStore.fetch()
            } catch (error) {
                /* empty */
            }
        }
        if (to.meta.public) {
            next()
            return
        } else if (!userStore.userInfo.id && to.name !== 'login') {
            next({ name: isMobile ? 'home' : 'login', query: { login: 'true' } })
        } else if (!userMemberStore.userMember.planId) {
            try {
                await userMemberStore.fetchMember()
                next()
            } catch (error) {
                next()
            }
        } else {
            next()
        }
    })
}