import type { Router } from "vue-router";

export function createRouterGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    if (to.meta.requiresAuth && !userStore.isAuthenticated) {
      if (from.path === "/auth/login") {
        return next("/");
      }
      const redirect = encodeURIComponent(to.fullPath);
      return next({ path: "/auth/login", query: { redirect } });
    }
    next();
  });
}
