export type LocationRow = {
  id: string
  parent_id: string | null
  value: string
  depth: number
  path: string[]
  is_active?: boolean | null
}

export function buildLocationChildrenMap(locations: LocationRow[]) {
  const map = new Map<string | null, LocationRow[]>()
  for (const location of locations) {
    const parentId = location.parent_id
    const list = map.get(parentId) ?? []
    list.push(location)
    map.set(parentId, list)
  }

  for (const [key, list] of map.entries()) {
    map.set(
      key,
      list.sort((a, b) => a.value.localeCompare(b.value, "es")),
    )
  }

  return map
}

export function getLocationPathIds({
  selectedByDepth,
  childrenMap,
}: {
  selectedByDepth: string[]
  childrenMap: Map<string | null, LocationRow[]>
}) {
  const path: string[] = []
  let parentId: string | null = null

  for (let depth = 0; depth < selectedByDepth.length; depth += 1) {
    const selectedId = selectedByDepth[depth]
    if (!selectedId) break
    const siblings = childrenMap.get(parentId) ?? []
    const selected = siblings.find((node) => node.id === selectedId)
    if (!selected) break
    path.push(selected.id)
    parentId = selected.id
  }

  return path
}
