export type PaginationItem =
  | { type: 'page'; page: number }
  | { type: 'ellipsis'; key: string }

export function buildPaginationItems(
  currentPage: number,
  pageCount: number,
  siblingCount = 1,
): PaginationItem[] {
  if (pageCount <= 1) {
    return []
  }

  const maxPagesWithoutEllipsis = siblingCount * 2 + 4
  if (pageCount <= maxPagesWithoutEllipsis) {
    return Array.from({ length: pageCount }, (_, index) => ({
      type: 'page' as const,
      page: index + 1,
    }))
  }

  const pages = new Set<number>([1, pageCount])

  for (let page = currentPage - siblingCount; page <= currentPage + siblingCount; page += 1) {
    if (page >= 1 && page <= pageCount) {
      pages.add(page)
    }
  }

  const sortedPages = [...pages].sort((left, right) => left - right)
  const items: PaginationItem[] = []
  let previousPage = 0

  for (const page of sortedPages) {
    if (previousPage > 0 && page - previousPage > 1) {
      items.push({ type: 'ellipsis', key: `ellipsis-${previousPage}-${page}` })
    }
    items.push({ type: 'page', page })
    previousPage = page
  }

  return items
}
