import {
  ReqWithPagination,
  ResWithPagination,
  ResWithPaginationOneItem,
} from './types';
import { AxiosResponse } from 'axios';
import {
  IBanner,
  ICategory,
  IProduct,
  IProductDetail,
} from '@/shared/types/testApi';
import httpClient from './httpClient';
import { ENDP_BANNER, ENDP_CATEGORY, ENDP_PRODUCT } from './URLs';

const getBanner = async (
  pagination?: ReqWithPagination,
): Promise<ResWithPagination<IBanner>['data']> => {
  const response: AxiosResponse<ResWithPagination<IBanner>> =
    await httpClient.get(ENDP_BANNER, { params: pagination });
  return response.data.data;
};

const getCategory = async (
  pagination?: ReqWithPagination,
): Promise<ResWithPagination<ICategory>['data']> => {
  const response: AxiosResponse<ResWithPagination<ICategory>> =
    await httpClient.get(ENDP_CATEGORY, { params: pagination });
  return response.data.data;
};

const getAllProduct = async (
  pagination?: ReqWithPagination,
): Promise<ResWithPagination<IProduct>['data']> => {
  const firstResponse: AxiosResponse<ResWithPagination<IProduct>> =
    await httpClient.get(ENDP_PRODUCT, { params: { ...pagination, page: 1 } });
  const pageCount = firstResponse.data.data.total_pages;
  const allResults = [...firstResponse.data.data.results];
  const requests = [];

  for (let i = 2; i <= pageCount; i++) {
    requests.push(
      httpClient.get<ResWithPagination<IProduct>>(ENDP_PRODUCT, {
        params: { ...pagination, page: i },
      }),
    );
  }

  const responses = await Promise.allSettled(requests);

  for (const res of responses) {
    if (res.status === 'fulfilled') {
      allResults.push(...res.value.data.data.results);
    } else {
      console.error('Error:', res.reason);
    }
  }

  return {
    ...firstResponse.data.data,
    results: allResults,
  };
};

const getProduct = async (
  pagination?: ReqWithPagination,
): Promise<ResWithPagination<IProduct>['data']> => {
  const response: AxiosResponse<ResWithPagination<IProduct>> =
    await httpClient.get(ENDP_PRODUCT, {
      params: pagination,
    });
  return response.data.data;
};

const getBestProduct = async (
  pagination?: ReqWithPagination,
): Promise<ResWithPagination<IProduct>['data']> => {
  const response: AxiosResponse<ResWithPagination<IProduct>> =
    await httpClient.get(ENDP_PRODUCT, {
      params: pagination,
    });
  return response.data.data;
};

const getOneProduct = async (
  id?: number,
  pagination?: ReqWithPagination,
): Promise<IProductDetail> => {
  const response: AxiosResponse<ResWithPaginationOneItem<IProductDetail>> =
    await httpClient.get(`${ENDP_PRODUCT}${id}`, { params: pagination });
  return response.data.data;
};

export {
  getBanner,
  getCategory,
  getProduct,
  getAllProduct,
  getOneProduct,
  getBestProduct,
};
