import type { RouteLocationNormalizedLoadedGeneric } from 'vue-router';

import { getTabKey } from '@easyflow/stores';

function resolveRouteResourceId(
  route: RouteLocationNormalizedLoadedGeneric,
): string {
  const rawId = route.params?.id ?? route.query?.id;
  const resourceId = Array.isArray(rawId) ? rawId[0] : rawId;
  return resourceId === null || resourceId === undefined
    ? ''
    : String(resourceId);
}

/**
 * 生成独立于页签分组语义的页面渲染 key。
 *
 * 同一个 pageKey 可以继续合并到同一页签，但不同路由组件或业务资源
 * 必须拥有不同的虚拟节点身份，避免 KeepAlive 复用错误页面。
 */
function getRouteViewKey(route: RouteLocationNormalizedLoadedGeneric): string {
  return JSON.stringify([
    getTabKey(route),
    route.name === null || route.name === undefined
      ? route.path
      : String(route.name),
    resolveRouteResourceId(route),
  ]);
}

/**
 * 判断当前路由是否应进入 KeepAlive 容器。
 *
 * 仅显式关闭缓存的路由绕过 KeepAlive，保留其余路由的既有行为。
 */
function shouldUseKeepAlive(
  route: RouteLocationNormalizedLoadedGeneric,
  keepAliveEnabled: boolean | undefined,
): boolean {
  return keepAliveEnabled === true && route.meta.keepAlive !== false;
}

export { getRouteViewKey, shouldUseKeepAlive };
