import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { emitter } from '../utils/eventBus'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: 'home'
        },
        {
            path: '/',
            name: 'index',
            component: () => import('@/views/TabView.vue'),
            children: [
                {
                    path: '/home',
                    name: 'home',
                    component: () => import('@/views/HomeView.vue'),
                    meta: {
                        allowGuest: true
                    }
                },
                {
                    path: '/watching',
                    name: 'watching',
                    component: () => import('@/views/WatchingView.vue'),
                    meta: {}
                },
                {
                    path: '/mine',
                    name: 'mine',
                    component: () => import('@/views/MineView.vue'),
                    meta: {}
                }
            ]
        },
        {
            path: '/history',
            name: 'history',
            component: () => import('@/views/HistoryView.vue')
        },
        {
            path: '/wallet',
            name: 'wallet',
            component: () => import('@/views/WalletView.vue')
        },
        {
            path: '/record',
            name: 'record',
            component: () => import('@/views/RecordView.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/LoginView.vue'),
            meta: {
                allowGuest: true
            }
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('@/views/RegisterView.vue'),
            meta: {
                allowGuest: true
            }
        },
        {
            path: '/video',
            name: 'video',
            component: () => import('@/views/VideoView.vue'),
            meta: {}
        }
    ],
    scrollBehavior(to, from, savedPosition) {
        console.log(to)
        return {
            left: 0,
            top: 0
        }
    }
})
router.beforeEach(async (to, from, next) => {
    const { user, get: getUser } = useUserStore()
    if (!to.meta.allowGuest && !user) {
        try {
            await getUser()
            next()
        } catch (error) {
            next(false)
            emitter.emit('promptLogin')
        }
    } else {
        if (!user) {
            getUser().catch(() => {})
        }
        next()
    }
})

export default router
