const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;

export interface Pagination {
  page: number;
  limit: number;
  skip: number;
  take: number;
}

export function parsePagination(query: Record<string, unknown>): Pagination {
  const page = Math.max(1, Math.trunc(Number(query.page)) || 1);
  const limit = Math.min(MAX_LIMIT, Math.max(1, Math.trunc(Number(query.limit)) || DEFAULT_LIMIT));
  return { page, limit, skip: (page - 1) * limit, take: limit };
}

export function paginatedResponse<T>(items: T[], total: number, { page, limit }: Pagination) {
  return { items, pagination: { page, limit, total, totalPages: Math.ceil(total / limit) } };
}
