import { cache } from 'react';

import { getProductCategories, listProducts } from '@lib/data';

import { loadCountryCodes } from './load-analyses';

async function categoryLoader({ handle }: { handle: string }) {
  const [response, countryCodes] = await Promise.all([
    getProductCategories({
      handle,
      limit: 1,
    }),
    loadCountryCodes(),
  ]);
  const category = response.product_categories[0];
  const countryCode = countryCodes[0]!;

  if (!response.product_categories?.[0]?.id) {
    return { category: null };
  }

  const {
    response: { products: categoryProducts },
  } = await listProducts({
    countryCode,
    queryParams: { limit: 100, category_id: response.product_categories[0].id },
  });

  return {
    category: {
      color:
        typeof category?.metadata?.color === 'string'
          ? category?.metadata?.color
          : 'primary',
      description: category?.description || '',
      handle: category?.handle || '',
      name: category?.name || '',
      countryCode,
      products: categoryProducts,
    },
  };
}
export const loadCategory = cache(categoryLoader);
