import { cache } from 'react';

import { getProductCategories } from '@lib/data/categories';
import { listProductTypes, listProducts } from '@lib/data/products';
import { listRegions } from '@lib/data/regions';

import { OrderAnalysisCard } from '../../_components/order-analyses-cards';

async function countryCodesLoader() {
  const countryCodes = await listRegions().then((regions) =>
    regions?.map((r) => r.countries?.map((c) => c.iso_2)).flat(),
  );
  return countryCodes ?? [];
}
export const loadCountryCodes = cache(countryCodesLoader);

async function productCategoriesLoader() {
  const productCategories = await getProductCategories({
    fields: '*products, *products.variants, is_active',
  });
  return productCategories.product_categories ?? [];
}
export const loadProductCategories = cache(productCategoriesLoader);

async function productTypesLoader() {
  const { productTypes } = await listProductTypes();
  return productTypes ?? [];
}
export const loadProductTypes = cache(productTypesLoader);

async function analysesLoader() {
  const [countryCodes, productCategories] = await Promise.all([
    loadCountryCodes(),
    loadProductCategories(),
  ]);
  const countryCode = countryCodes[0]!;

  const category = productCategories.find(
    ({ metadata }) => metadata?.page === 'order-analysis',
  );
  const categoryProducts = category
    ? await listProducts({
        countryCode,
        queryParams: { limit: 100, category_id: category.id, order: 'title' },
      })
    : null;

  return {
    analyses:
      categoryProducts?.response.products
        .filter(
          ({ status, metadata }) =>
            status === 'published' && !!metadata?.analysisIdOriginal,
        )
        .map<OrderAnalysisCard>(
          ({ title, description, subtitle, variants }) => {
            const variant = variants![0]!;
            return {
              title,
              description,
              subtitle,
              variant: {
                id: variant.id,
              },
              price: variant.calculated_price?.calculated_amount ?? null,
            };
          },
        ) ?? [],
    countryCode,
  };
}
export const loadAnalyses = cache(analysesLoader);
