import { Ref, ref } from 'vue';
import {
  RouteLocationNormalizedLoaded,
  RouteLocationRaw,
  useRouter,
} from 'vue-router';

const historyRoutes: Ref<RouteLocationNormalizedLoaded[]> = ref([]);

export const useRouterHistory = () => {
  const router = useRouter();

  const goBack = async (fallback?: RouteLocationRaw) => {
    if (historyRoutes.value.length === 0) {
      console.warn(
        'You need to install the RouterHistory plugin. See Readme#router-history for more info',
      );
      throw new Error('History Router plugin is not installed');
    }
    if (historyRoutes.value.length > 1) {
      const target = historyRoutes.value[historyRoutes.value.length - 2];
      historyRoutes.value = historyRoutes.value.slice(0, -2);
      await router.push(target);
    } else {
      historyRoutes.value = [];
      await router.push(fallback || { path: '/' });
    }
  };

  const addHistoryRoute = (route: RouteLocationNormalizedLoaded) => {
    const lastRoute = historyRoutes.value.at(-1);
    if (
      lastRoute &&
      ((lastRoute.name && lastRoute.name === route.name) ||
        (lastRoute.path && lastRoute.path === route.path))
    ) {
      historyRoutes.value.pop();
    }
    historyRoutes.value.push(route);
  };

  return {
    historyRoutes,
    addHistoryRoute,
    goBack,
  };
};
