import axios, { AxiosRequestConfig } from 'axios';

async function getData(params: any, url: string, axiosParams?: AxiosRequestConfig) {
  try {
    const response = await axios({
      url: url,
      method: 'get',
      params: {
        limit: 10,
        ...params,
      },
      ...(axiosParams ? axiosParams : {}),
    });
    return response;
  } catch (error) {
    console.log(error);
  }
}

interface Result {
  currentPage: number;
  data: any[];
}

async function manipulatedGenerateDataPagination(
  url: string,
  params: any,
  prevData: any[] = [],
  currentPage = 1,
  axiosParams?: AxiosRequestConfig,
): Promise<Result> {
  try {
    const response = await getData({ ...params, page: currentPage }, url, axiosParams);

    const data = response?.data?.data ?? [];
    const meta = response?.data?.meta;

    if (meta.totalPages <= currentPage) {
      return {
        currentPage: currentPage,
        data: [...prevData, ...data],
      };
    } else {
      const response2 = await manipulatedGenerateDataPagination(
        url,
        params,
        [...prevData, ...data],
        currentPage + 1,
        axiosParams,
      );
      const data2: any[] = response2?.data ?? [];
      const newCurrentPage: number = response2?.currentPage;
      return {
        currentPage: newCurrentPage,
        data: data2,
      };
    }
  } catch (error) {
    return {
      currentPage: 1,
      data: prevData,
    };
  }
}

interface GenerateDataPagination {
  url: string;
  params: any;
  axiosParams?: AxiosRequestConfig;
}

export async function generateDataPagination(props: GenerateDataPagination): Promise<Result> {
  const { url, params = {}, axiosParams } = props;
  const data = await manipulatedGenerateDataPagination(url, params, [], 1, axiosParams);
  return data;
}
