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

/**
 * @param {Record<string, any>} kaskoConfig
 * @returns {Promise<{
 *  id: string,
 *  productName: string,
 *  contents: Record<string, any>,
 *  items: any[],
 *  manifest: Record<string, any>
 * }>}
 */
async function getProduct(kaskoConfig) {
  const url = `${kaskoConfig.feApiUrl}/integrations/${kaskoConfig.touchpointId}`;
  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 product data');
  }

  return {
    id: data.id || kaskoConfig.touchpointId,
    productName: data.content.item_title || data.id || kaskoConfig.touchpointId,
    contents: data.content || {},
    items: data.items || [],
    manifest: data.webapp_manifest || {},
  };
}

module.exports = getProduct;
