import { defineRouter } from '#q-app/wrappers';
import { createMemoryHistory, createRouter, createWebHashHistory, createWebHistory, } from 'vue-router';
import routes from './routes';
import { useAuthStore } from 'src/stores/auth-store';
import { RouteNames } from 'src/router/router-constants';
import { useChatbotStore } from 'src/stores/chatbot-store';
import type { UserModuleAccess } from 'src/modules/shared/models/user.models';

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default defineRouter(function (/* { store, ssrContext } */) {
    const createHistory = process.env.SERVER
        ? createMemoryHistory
        : (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);

    const Router = createRouter({
        scrollBehavior: () => ({ left: 0, top: 0 }),
        routes,

        // Leave this as is and make changes in quasar.conf.js instead!
        // quasar.conf.js -> build -> vueRouterMode
        // quasar.conf.js -> build -> publicPath
        history: createHistory(process.env.VUE_ROUTER_BASE),
    });

    Router.beforeEach(async (destination_page) => {
        const auth_store = useAuthStore();
        const result = await auth_store.getProfile() ?? { status: 400, message: 'unknown error occured' };

        if (destination_page.meta.requires_auth && !auth_store.user || (result.status >= 400 && destination_page.name !== RouteNames.LOGIN)) {
            console.error('no user account found');
            return { name: 'login' };
        } 
        
        if (destination_page.meta.required_module && auth_store.user) {
            if (!auth_store.user.user_module_access.includes(destination_page.meta.required_module as UserModuleAccess)) 
                return {name: 'error'};
        } 
    })

    Router.afterEach( (destination_page) => {
        const auth_store = useAuthStore();

        if (auth_store.user?.user_module_access.includes('chatbot')) {
            const chatbot_store = useChatbotStore();
            chatbot_store.updatePageContext(destination_page.name as RouteNames);
        }
    })

    return Router;
});
