// handle route history
import type {
  NavigationGuard,
  RouteLocationNormalized,
  RouteLocationRaw,
  Router,
} from "vue-router";

const routeHistory: RouteLocationNormalized[] = [];
const MAX_HISTORY = 10; // for example, store the last 10 visited routes
let isFirstNavigation = true;

export const addToHistory: NavigationGuard = (to, from, next) => {
  // Add the current route to the history, and ensure it doesn't exceed the maximum length
  if (isFirstNavigation) {
    isFirstNavigation = false;
  } else {
    routeHistory.push(from);
  }
  if (routeHistory.length > MAX_HISTORY) {
    routeHistory.shift();
  }
  next();
};

export function getPreviousRoute() {
  if (routeHistory.length > 0) {
    return routeHistory[routeHistory.length - 1];
  }
  return undefined;
}

export function routerBackOrFallback(router: Router, fallbackRoute: RouteLocationRaw) {
  // Check the latest route in history
  const previousRoute = getPreviousRoute();
  if (previousRoute) {
    router.back();
  } else {
    router.push(fallbackRoute);
  }
}
