import { profileNextRoute } from "@/services/onboarding";
import { useUserStore } from "@/stores/user";
import type { NavigationGuardNext, RouteLocationNormalized } from "vue-router";
import { START_LOCATION } from "vue-router";

export async function onboardingRedirect(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const user = useUserStore();

  // Guest
  if (!user.loggedIn) {
    if (to.name !== "accountCreate") {
      return next({ name: "accountCreate", params: to.params });
    }
    return next();
  }

  // Member
  if (to.name === "accountCreate") {
    return next({ name: "accountConfirm", params: to.params });
  }

  if (to.name === "accountConfirm") {
    return next();
  }

  // Maybe we can skip the profile step
  if (from === START_LOCATION && user.organisation && to.name === "accountProfile") {
    return next({ name: profileNextRoute(to.params.courseType), params: to.params });
  }

  return next();
}
