import type { MenuItem } from '@rutatiina/ui/types/navigation';

/**
 * Fills the placeholders a server-registered path may contain, e.g.
 * `/users/{user}/logs` with `{ user: 12 }`.
 */
export function resolvePath(
  path: string,
  params: Record<string, string | number> = {},
): string {
  return path.replace(/\{(\w+)\}/g, (match, key: string) =>
    key in params ? String(params[key]) : match,
  );
}

/**
 * A copy of the menu with every path resolved against the given parameters.
 */
export function resolveMenu(
  items: MenuItem[],
  params: Record<string, string | number>,
): MenuItem[] {
  return items.map((item) => ({
    ...item,
    ...(item.path ? { path: resolvePath(item.path, params) } : {}),
    ...(item.children ? { children: resolveMenu(item.children, params) } : {}),
  }));
}
