import type { DriveFile } from "@/lib/types";

export type DriveFolderNode = DriveFile & {
  children: DriveFolderNode[];
};

export function buildDriveFolderTree(items: DriveFile[]): DriveFolderNode[] {
  const byId = new Map<string, DriveFolderNode>();
  for (const item of items) {
    byId.set(item.id, { ...item, children: [] });
  }
  const roots: DriveFolderNode[] = [];
  for (const node of byId.values()) {
    const parentId = node.parent_ids.find((id) => byId.has(id));
    if (parentId) {
      byId.get(parentId)!.children.push(node);
    } else {
      roots.push(node);
    }
  }
  const sortNodes = (nodes: DriveFolderNode[]) => {
    nodes.sort((left, right) => left.name.localeCompare(right.name));
    for (const node of nodes) sortNodes(node.children);
  };
  sortNodes(roots);
  return roots;
}

export function findDriveFolderPath(nodes: DriveFolderNode[], targetId: string, trail: string[] = []): string[] {
  for (const node of nodes) {
    const nextTrail = [...trail, node.name];
    if (node.id === targetId) return nextTrail;
    const childTrail = findDriveFolderPath(node.children, targetId, nextTrail);
    if (childTrail.length) return childTrail;
  }
  return [];
}

export function findDriveFolderBreadcrumbs(
  nodes: DriveFolderNode[],
  targetId: string,
  trail: Array<{ id: string; name: string }> = []
): Array<{ id: string; name: string }> {
  for (const node of nodes) {
    const nextTrail = [...trail, { id: node.id, name: node.name }];
    if (node.id === targetId) return nextTrail;
    const childTrail = findDriveFolderBreadcrumbs(node.children, targetId, nextTrail);
    if (childTrail.length) return childTrail;
  }
  return [];
}

export function findDriveFolderParentId(nodes: DriveFolderNode[], targetId: string, parentId = ""): string {
  for (const node of nodes) {
    if (node.id === targetId) return parentId;
    const childParent = findDriveFolderParentId(node.children, targetId, node.id);
    if (childParent) return childParent;
  }
  return "";
}
