import { hasPermissions } from "#shared/auth.util";

export default defineNuxtRouteMiddleware(async (to, from) => {
    const { loggedIn, fetch, user } = useUserSession();
    const { fetch: fetchContent } = useContent();
    const meta = to.meta;

    if(await fetch())
    {
        fetchContent(true);
    }
    
    if(!!meta.guestsGoesTo && !loggedIn.value)
    {
        return navigateTo(meta.guestsGoesTo);
    }
    else if(meta.requireAuth && !loggedIn.value)
    {
        return abortNavigation({ statusCode: 401, message: 'Unauthorized', });
    }
    else if(!!meta.usersGoesTo && loggedIn.value)
    {
        return navigateTo(meta.usersGoesTo);
    }
    else if(!!meta.validState && (!loggedIn.value || (user.value?.state ?? 0) === 0))
    {
        return abortNavigation({ statusCode: 401, message: 'Unauthorized', });
    }
    else if(!!meta.rights)
    {
        if(!user.value)
        {
            return abortNavigation({ statusCode: 401, message: 'Unauthorized', });
        }
        else if(!hasPermissions(user.value.permissions, meta.rights))
        {
                return abortNavigation({ statusCode: 401, message: 'Unauthorized', });
        }
    }

    return;
});