type OrderLike = {
  status: string
  createdAt: string
}

export function groupOrdersByStatus<T extends OrderLike>(items: T[], statuses: readonly string[]) {
  const byStatus = new Map<string, T[]>()
  for (const status of statuses) byStatus.set(status, [])

  for (const item of items) {
    const list = byStatus.get(item.status) ?? []
    list.push(item)
    byStatus.set(item.status, list)
  }

  return statuses
    .map((status) => ({
      status,
      items: (byStatus.get(status) ?? []).sort(
        (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
      ),
    }))
    .filter((group) => group.items.length > 0)
}
