const axios = require('../../axios');

/**
 * @param {Record<string, any>} kaskoConfig
 * @param {Record<string, any>} item
 * @returns {Promise<Record<string, any>>}
 */
async function getSubProduct(kaskoConfig, item) {
  const url = `${kaskoConfig.feApiUrl}/integrations/${kaskoConfig.touchpointId}/subproducts/${item.id}`;
  const { data } = await axios
    .get(url, {
      params: {
        language: kaskoConfig.language,
        key: kaskoConfig.publicKey,
        product_version: kaskoConfig.productVersionId,
        integration_version: kaskoConfig.integrationVersionId,
      },
    })
    .catch((error) => {
      throw error;
    });

  if (!data) {
    throw new Error('No item data');
  }

  return {
    id: data.id || item.id,
    name: data.content.item_title || data.id || item.id,
    contents: data.content || {},
    fields: data.field_definition || [],
    manifest: data.manifest || {},
  };
}

module.exports = getSubProduct;
