import { useLoginStore } from "@/pinia/auth/login/login.store"
import { storeToRefs } from "pinia";

export default defineNuxtRouteMiddleware(async (to, from) => {
    const { me, getUserSessionActive } = useLoginStore();
    const { user } = storeToRefs(useLoginStore());
    const protected_routes = ['/profile', '/cart'];
    const routes_blocked_with_user = ['/login', '/register', '/forgot', '/activated_account'];

    const is_login = await getUserSessionActive();
    
    if(!is_login) {
        user.value = null;
    }

    if(!is_login && protected_routes.includes(to.path)) {
        return navigateTo('/')
    }

    if(is_login && !user.value) {
        await me();
    }

    // Se validan las rutas bloqueadas por tener una sesión activa
    if(is_login && routes_blocked_with_user.includes(to.path)) {
        return navigateTo('/');
    }
    
})