import type { RouteLocationRaw } from "vue-router";
import { router } from "../router/index.ts";

interface LoginNavigateOptions {
  redirect?: RouteLocationRaw;
}

function navigate(location: RouteLocationRaw, replace = false) {
  if (typeof window === "undefined") {
    return Promise.resolve(router.resolve(location));
  }

  return replace ? router.replace(location) : router.push(location);
}

function resolveRedirect(redirect?: RouteLocationRaw): string | null {
  const target = redirect ?? router.currentRoute.value.fullPath;
  const resolved =
    typeof target === "string" ? target : router.resolve(target).fullPath;

  if (
    !resolved ||
    !resolved.startsWith("/") ||
    resolved.startsWith("//") ||
    resolved.startsWith("/login")
  ) {
    return null;
  }

  return resolved;
}

export const goHome = () => {
  return navigate({ name: "home" });
};

export const goLogin = (options: LoginNavigateOptions = {}) => {
  const redirect = resolveRedirect(options.redirect);
  const location = redirect
    ? { name: "login", query: { redirect } }
    : { name: "login" };

  if (router.currentRoute.value.name === "login") {
    return navigate(location, true);
  }

  return navigate(location);
};

export const goBack = () => {
  return router.back();
};
