export interface HierarchyNode {
  id: string | null;
  title: string | null;
  children: Hierarchy | null;
}
type Hierarchy = Record<string, HierarchyNode>;

function addToHierarchy(
  tree: Hierarchy,
  [noteId, title]: [string, string],
): Hierarchy {
  const path = noteId.split("/");
  if (path.length === 0 || path[0] === "") {
    return tree;
  }

  if (!tree[path[0]]) {
    tree[path[0]] = { id: null, title: null, children: null };
  }
  let curr = tree[path[0]];

  for (const node of path.slice(1)) {
    curr.children ||= {};
    if (!curr.children[node]) {
      curr.children[node] = { id: null, title: null, children: null };
    }
    curr = curr.children[node];
  }

  curr.id = noteId;
  curr.title = title;
  return tree;
}

export function makeHierarchy(notes: Array<[string, string]>): Hierarchy {
  return notes.reduce(addToHierarchy, {});
}
