const RENDITION = 'c_limit,cs_srgb,h_500,w_500'
const DEFAULT_LOCALE = 'en-US'
const LOCALE = document.documentElement.lang ?? DEFAULT_LOCALE

export default function processProducts (products) {
  const processedProducts = []
  for (const product of products) {
    let image = get(product, 'Main Image')
    if (image) {
      const index = image.lastIndexOf('/')
      image = `${image.slice(0, index + 1)}${RENDITION}/${image.slice(index + 1)}`
    }

    const links = []
    const features = []
    for (const key of Object.keys(product)) {
      if (key.startsWith('Buy Now Label')) {
        const name = get(product, key)
        const value = get(product, key.replace('Label', 'Link'))
        links.push({ name, value })
      }

      if (key.startsWith('Key Feature')) {
        const value = get(product, key)
        value && features.push(value)
      }
    }

    // Randomize links order.
    // eslint-disable-next-line sonarjs/pseudo-random
    links.sort(() => Math.random() - 0.5) // NOSONAR

    processedProducts.push({
      id: get(product, 'Salsify Unique ID'),
      name: get(product, 'Product Name'),
      description: get(product, 'Product Description'),
      category: get(product, 'Product Category'),
      subcategory: get(product, 'Product Subcategory'),
      viscosity: get(product, 'Viscosity'),
      'product-line': get(product, 'Product Line'),
      image,
      features,
      links
    })
  }

  processedProducts.sort((a, b) => a.id.localeCompare(b.id))
  return processedProducts
}

function get (product, key) {
  return product[key]?.[LOCALE] ?? product[key]?.[DEFAULT_LOCALE]
}
