import { cache } from 'react'; import { getAnalysisElementOriginalIds, listProductTypes, listProducts } from "@lib/data/products"; import { listRegions } from '@lib/data/regions'; import { AnalysisElement, getAnalysisElements } from '~/lib/services/analysis-element.service'; 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 productTypesLoader() { const { productTypes } = await listProductTypes(); return productTypes ?? []; } export const loadProductTypes = cache(productTypesLoader); async function analysisPackagesLoader() { const [countryCodes, productTypes] = await Promise.all([loadCountryCodes(), loadProductTypes()]); const countryCode = countryCodes[0]!; const productType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages'); if (!productType) { return { analysisElements: [], analysisPackages: [], countryCode }; } const { response } = await listProducts({ countryCode, queryParams: { limit: 100, "type_id[0]": productType.id }, }); const analysisPackages = response.products; let analysisElements: AnalysisElement[] = []; const analysisElementOriginalIds = await getAnalysisElementOriginalIds(analysisPackages); if (analysisElementOriginalIds.length) { analysisElements = await getAnalysisElements({ originalIds: analysisElementOriginalIds }); } return { analysisElements, analysisPackages, countryCode }; } export const loadAnalysisPackages = cache(analysisPackagesLoader);