import {createRouter, createWebHistory} from "vue-router/dist/vue-router";

import routes from './routes'
import store from "@/store/index";
import { appConfig } from "@/config/env";
import { defaultAuthenticatedRoute } from "@/config/app-shell";


const router = createRouter({
    history: createWebHistory(),
    routes: routes,
})
router.beforeEach((to, from, next) => {
    const next_method = async () => {
        store.state.common.loading = true
        if(import.meta.env.PROD || import.meta.env.DEV){
            const access_page = ['login']
            let token = await store.state.directus.client.getToken()
            if(!token){
                try {
                    await store.state.directus.client.refresh()
                }catch (e) {
                    await store.commit('directus/client')
                }
                token = await store.state.directus.client.getToken()
            }
            if(token || access_page.includes(to.name) ){
                if(token){
                    store.state.user.isLogin = true
                    if(!store.state.user.user_info)
                        await store.dispatch("user/getUserInfo")
                    if(!store.state.user.corporate_customer)
                        await store.dispatch("user/getCorporateList")
                }else {
                    store.state.user.isLogin=false
                }
                store.state.common.loading = false
                if(token && to.name.includes('login'))
                    next(defaultAuthenticatedRoute)
                next()
            }else{
                store.state.user.isLogin=false
                store.state.common.loading = false
                next({
                    name:"login"
                })
            }

        }else{
            await store.state.directus.client.setToken(appConfig.directusDebugToken)
            store.state.user.isLogin = true
            if(!store.state.user.user_info)
                await store.dispatch("user/getUserInfo")
            if(!store.state.user.corporate_customer)
                await store.dispatch("user/getCorporateList")
            store.state.common.loading = false
            next()
        }
    }
    next_method()
})

export default {
    router,
}
