import router from '@/router';
import { IDPool } from '@/utils';
import type { PageErrorReason, PageErrorType } from '@/views/ErrorPage.vue';
import { defineStore } from 'pinia';
import { computed } from 'vue';
import {
  type RouteLocationNormalized,
  type RouteLocationRaw,
  type RouteRecordRaw,
} from 'vue-router';

export const tempErrorRouteName = '_TempError';
export const usePageStore = defineStore('page', () => {
  const routeIdPool = new IDPool();
  const routeIds = routeIdPool.usedIDSet;
  const pageLoadingCount = computed(() => routeIds.size);

  function setNewRouteId(route: RouteLocationNormalized) {
    return (route.meta.routeId = routeIdPool.newID());
  }

  function removeRouteId(route: RouteLocationNormalized) {
    const { routeId } = route.meta;
    if (routeId === undefined) {
      return;
    }
    routeIdPool.removeID(routeId);
  }

  function createTempErrorRoute(
    reason: Exclude<
      PageErrorReason,
      {
        type: PageErrorType.NOT_FOUND;
      }
    >,
    to: RouteLocationNormalized,
  ): RouteLocationRaw {
    const tempErrorRoute: RouteRecordRaw = {
      path: to.fullPath,
      name: tempErrorRouteName,
      component: () => import('@/views/ErrorPage.vue'),
      props: reason,
    };
    router.addRoute(tempErrorRoute);
    removeRouteId(to);
    return { name: tempErrorRouteName, replace: true };
  }

  return {
    pageLoadingCount,
    setNewRouteId,
    removeRouteId,
    createTempErrorRoute,
  };
});
