import { sdk } from '@lib/config';
import { HttpTypes } from '@medusajs/types';

import { getCacheOptions } from './cookies';

export const listCategories = async (query?: Record<string, any>) => {
  const next = {
    ...(await getCacheOptions('categories')),
  };

  const limit = query?.limit || 100;

  return sdk.client
    .fetch<{ product_categories: HttpTypes.StoreProductCategory[] }>(
      '/store/product-categories',
      {
        query: {
          fields:
            '*category_children, *products, *parent_category, *parent_category.parent_category',
          limit,
          ...query,
        },
        next,
      },
    )
    .then(({ product_categories }) => product_categories);
};

export const getCategoryByHandle = async (categoryHandle: string[]) => {
  const { product_categories } = await getProductCategories({
    handle: `${categoryHandle.join('/')}`,
    limit: 1,
  });
  return product_categories[0];
};

export const getProductCategories = async ({
  handle,
  limit,
  fields = '*category_children, *products',
}: {
  handle?: string;
  limit?: number;
  fields?: string;
} = {}) => {
  const next = {
    ...(await getCacheOptions('categories')),
  };

  return sdk.client.fetch<HttpTypes.StoreProductCategoryListResponse>(
    `/store/product-categories`,
    {
      query: {
        fields,
        handle,
        limit,
      },
      next,
    },
  );
};
