import {createRouter, createWebHistory} from 'vue-router'
import Index from '@/views/Index.vue';
import Login from '@/views/Login.vue';
import Register from '@/views/Register.vue';
import store from '@/store';


const routes = [
    {path: '/', component: Index, meta: {requiresAuth: true}},
    {path: '/login', component: Login, meta: {requiresAuth: false}},
    {path: '/register', component: Register, meta: {requiresAuth: false}},
]

const router = createRouter({
    // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
    history: createWebHistory(),
    linkActiveClass: "active",
    routes, // short for `routes: routes`
})

router.beforeEach((to/*, from*/) => {
    // instead of having to check every route record with
    // to.matched.some(record => record.meta.requiresAuth)
    if (to.meta.requiresAuth && !store.getters.isLoggedIn) {
        // this route requires auth, check if logged in
        // if not, redirect to login page.
        console.log("Not logged in, redirecting to login page")
        return {
            path: '/login',
            // save the location we were at to come back later
            query: {redirect: to.fullPath},
        }
    }
})

export default router