import { PaginationOptions, PaginationResult } from '../types';

export function calculatePagination(options: PaginationOptions): PaginationResult {
  const { totalItems, currentPage, pageSize } = options;
  
  const totalPages = Math.ceil(totalItems / pageSize);
  const normalizedCurrentPage = Math.max(1, Math.min(currentPage, totalPages));
  
  const startIndex = (normalizedCurrentPage - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, totalItems);
  
  return {
    currentPage: normalizedCurrentPage,
    totalPages,
    pageSize,
    totalItems,
    hasNextPage: normalizedCurrentPage < totalPages,
    hasPreviousPage: normalizedCurrentPage > 1,
    startIndex,
    endIndex
  };
}

export function generatePageNumbers(currentPage: number, totalPages: number, maxPages: number = 5): number[] {
  const pages: number[] = [];
  const halfMaxPages = Math.floor(maxPages / 2);
  
  let startPage = Math.max(currentPage - halfMaxPages, 1);
  const endPage = Math.min(startPage + maxPages - 1, totalPages);
  
  if (endPage - startPage + 1 < maxPages) {
    startPage = Math.max(endPage - maxPages + 1, 1);
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }
  
  return pages;
}

export function getPageItems<T>(items: T[], currentPage: number, pageSize: number): T[] {
  const startIndex = (currentPage - 1) * pageSize;
  return items.slice(startIndex, startIndex + pageSize);
}