import type { RouteLocation, Router } from "vue-router";
import authRoutes from "./auth";

function isAuthRoute(route: RouteLocation) {
  return authRoutes.some(r => r.path === route.path);
}

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

    if (isAuthRoute(to) && userStore.isAuthenticated) {
      return next("/");
    }
    next();
  });
}
