import { cache } from 'react';

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

import { ServiceCategory } from '../../_components/service-categories';

async function ttoServicesLoader() {
  const response = await getProductCategories({
    fields: '*products, is_active, metadata',
  });

  const heroCategories = response.product_categories?.filter(
    ({ parent_category, metadata }) =>
      parent_category?.handle === 'tto-categories' && metadata?.isHero,
  );

  const ttoCategories = response.product_categories?.filter(
    ({ parent_category, metadata }) =>
      parent_category?.handle === 'tto-categories' && !metadata?.isHero,
  );

  return {
    heroCategories:
      heroCategories.map<Omit<ServiceCategory, 'countryCode'>>(
        ({ name, handle, metadata, description, products }) => ({
          name,
          handle,
          color:
            typeof metadata?.color === 'string' ? metadata.color : 'primary',
          description,
          products: products ?? [],
        }),
      ) ?? [],
    ttoCategories:
      ttoCategories.map<Omit<ServiceCategory, 'countryCode'>>(
        ({ name, handle, metadata, description, products }) => ({
          name,
          handle,
          color:
            typeof metadata?.color === 'string' ? metadata.color : 'primary',
          description,
          products: products ?? [],
        }),
      ) ?? [],
  };
}
export const loadTtoServices = cache(ttoServicesLoader);
