import type { Category, FlatCategory } from '../types/category'

export function flattenCategories(categories: Category[]): FlatCategory[] {
  const result: FlatCategory[] = []

  function walk(parentId: string | null, depth: number) {
    const children = categories
      .filter((c) => c.parentId === parentId)
      .sort((a, b) => a.nameEn.localeCompare(b.nameEn))

    for (const child of children) {
      result.push({ ...child, depth })
      walk(child.id, depth + 1)
    }
  }

  walk(null, 0)
  return result
}

export function getDescendantIds(categories: Category[], id: string): string[] {
  const ids: string[] = [id]
  const children = categories.filter((c) => c.parentId === id)
  for (const child of children) {
    ids.push(...getDescendantIds(categories, child.id))
  }
  return ids
}

export function getChildren(categories: Category[], parentId: string | null): Category[] {
  return categories
    .filter((c) => c.parentId === parentId)
    .sort((a, b) => a.nameEn.localeCompare(b.nameEn))
}

export function hasChildren(categories: Category[], id: string): boolean {
  return categories.some((c) => c.parentId === id)
}
