export const SETTINGS_PAGE_SIZE = 8;

export type SearchParams = Record<string, string | string[] | undefined>;

export function getSearchParam(params: SearchParams, key: string): string {
  const value = params[key];
  if (Array.isArray(value)) {
    return value[0] ?? "";
  }

  return value ?? "";
}

export function getPage(params: SearchParams): number {
  const page = Number(getSearchParam(params, "page"));
  return Number.isInteger(page) && page > 0 ? page : 1;
}

export function getPageCount(total: number, pageSize = SETTINGS_PAGE_SIZE): number {
  return Math.max(1, Math.ceil(total / pageSize));
}

export function paginate<T>(items: T[], page: number, pageSize = SETTINGS_PAGE_SIZE): T[] {
  const safePage = Math.min(page, getPageCount(items.length, pageSize));
  return items.slice((safePage - 1) * pageSize, safePage * pageSize);
}

export function buildPageHref(pathname: string, query: string, page: number): string {
  const params = new URLSearchParams();
  if (query.trim()) {
    params.set("q", query.trim());
  }
  params.set("page", String(page));
  return `${pathname}?${params.toString()}`;
}
