import type { ApiUnifiedFolder } from '@/lib/api/types'
import type { FolderTreeNode } from '@/lib/sidebar-nav-maps'

export function buildFolderTreeFromUnified(folders: ApiUnifiedFolder[]): FolderTreeNode[] {
  const byParent = new Map<string | null, ApiUnifiedFolder[]>()

  for (const folder of folders) {
    const parentKey = folder.parent_id ?? null
    const list = byParent.get(parentKey) ?? []
    list.push(folder)
    byParent.set(parentKey, list)
  }

  const walk = (parentId: string | null): FolderTreeNode[] => {
    const nodes = byParent.get(parentId) ?? []
    return nodes
      .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.name.localeCompare(b.name))
      .map((folder) => ({
        id: folder.id,
        label: folder.name,
        color: folder.color || undefined,
        children: walk(folder.id),
      }))
  }

  return walk(null)
}

export function mergeUnifiedFolderTrees(
  globalFolders: ApiUnifiedFolder[],
  accountFolders: ApiUnifiedFolder[]
): FolderTreeNode[] {
  return [
    ...buildFolderTreeFromUnified(globalFolders),
    ...buildFolderTreeFromUnified(accountFolders),
  ]
}
