import type { FolderTreeNode } from '@/lib/sidebar-nav-maps'
import type { LabelRowItem } from '@/lib/sidebar-nav-data'
import { isSystemNavLabelId } from '@/lib/sidebar-nav-data'
import { isServerNavId } from '@/lib/sidebar-nav-server-id'

export type LabelReorderItem = { id: string; sort_order: number }
export type UnifiedFolderReorderItem = {
  id: string
  sort_order: number
  parent_id: string | null
}

export function labelRowsToReorderItems(rows: LabelRowItem[]): LabelReorderItem[] {
  return rows
    .filter((row) => isServerNavId(row.id) && !isSystemNavLabelId(row.id))
    .map((row, index) => ({ id: row.id, sort_order: index * 10 }))
}

export function folderTreeToReorderItems(
  tree: FolderTreeNode[],
  parentId: string | null = null
): UnifiedFolderReorderItem[] {
  const items: UnifiedFolderReorderItem[] = []
  tree.forEach((node, index) => {
    if (!isServerNavId(node.id)) return
    items.push({
      id: node.id,
      sort_order: index * 10,
      parent_id: parentId,
    })
    if (node.children?.length) {
      items.push(...folderTreeToReorderItems(node.children, node.id))
    }
  })
  return items
}

export function hasServerReorderItems(items: LabelReorderItem[] | UnifiedFolderReorderItem[]): boolean {
  return items.length > 0
}
