import { useCourseSessionsStore } from "@/stores/courseSessions";
import { useUserStore } from "@/stores/user";
import type { NavigationGuard, RouteLocationNormalized } from "vue-router";

export const updateLoggedIn: NavigationGuard = async () => {
  const loggedIn = getCookieValue("loginStatus") === "true";
  const userStore = useUserStore();

  userStore.$patch({ loggedIn });
  if (loggedIn && !userStore.id) {
    await userStore.fetchUser();
  }
};

export const redirectToLoginIfRequired: NavigationGuard = (to) => {
  const userStore = useUserStore();
  if (loginRequired(to) && !userStore.loggedIn) {
    const appEnv = import.meta.env.VITE_APP_ENVIRONMENT || "local";
    const ssoLogin = appEnv.startsWith("prod") || appEnv.startsWith("stage");
    return ssoLogin ? `/login?next=${to.fullPath}` : `/login-local?next=${to.fullPath}`;
  }
};

export const getCookieValue = (cookieName: string): string => {
  // https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript
  const cookieValue = document.cookie.match(
    "(^|[^;]+)\\s*" + cookieName + "\\s*=\\s*([^;]+)"
  );
  if (!cookieValue) {
    return "";
  }
  return cookieValue.pop() || "";
};

const loginRequired = (to: RouteLocationNormalized) => {
  return !to.meta?.public;
};

export const expertRequired: NavigationGuard = (to: RouteLocationNormalized) => {
  const courseSessionsStore = useCourseSessionsStore();
  if (courseSessionsStore.currentCourseSessionHasCockpit) {
    return true;
  } else {
    const courseSlug = to.params.courseSlug as string;
    return `/course/${courseSlug}/learn`;
  }
};

export async function handleCourseSessions(to: RouteLocationNormalized) {
  // register after login hooks
  const courseSessionsStore = useCourseSessionsStore();
  if (to.params.courseSlug) {
    courseSessionsStore._currentCourseSlug = to.params.courseSlug as string;
  } else {
    courseSessionsStore._currentCourseSlug = "";
  }
  if (!courseSessionsStore.loaded) {
    await courseSessionsStore.loadCourseSessionsData();
  }
}
