import { AxiosResponse } from 'axios';

import { Pagination } from 'src/types/services';

export const findIndexOnPages = <TData>(
  pages: AxiosResponse<TData[]>[],
  compare: (element: TData) => boolean,
): [pageIndex: number, elementIndex: number] => {
  if (!pages) return [-1, -1];

  for (let i = 0; i < pages.length; i++) {
    const elementIndex = pages[i]?.data?.findIndex(compare);
    if (elementIndex !== undefined && elementIndex !== -1) {
      return [i, elementIndex];
    }
  }

  return [-1, -1];
};

export const findIndexOnPaginatedPages = <TData>(
  pages: AxiosResponse<Pagination<TData[]>>[],
  compare: (element: TData) => boolean,
): [pageIndex: number, elementIndex: number] => {
  if (!pages) return [-1, -1];

  for (let i = 0; i < pages.length; i++) {
    const elementIndex = pages[i]?.data?.items?.findIndex(compare);
    if (elementIndex !== undefined && elementIndex !== -1) {
      return [i, elementIndex];
    }
  }

  return [-1, -1];
};
