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

const getProduct = require('./getProduct');
const getTouchpoint = require('./getTouchpoint');
const getWebappConfig = require('./getWebappConfig');

/**
 * @param {string} url
 * @returns {Promise<Record<string, any>>}
 */
async function getWebappData(url) {
  const { data } = await axios.get(url).catch((error) => {
    throw error;
  });

  if (typeof data !== 'string' || !data) {
    throw new Error("Webapp couldn't be loaded");
  }

  const kaskoConfig = await getWebappConfig(data);

  if (
    !(
      kaskoConfig.touchpointId &&
      kaskoConfig.publicKey &&
      kaskoConfig.feApiUrl &&
      kaskoConfig.language
    )
  ) {
    throw new Error('Unsupported webapp configuration');
  }

  if (/^in_/.test(kaskoConfig.touchpointId)) {
    const touchpointData = await getProduct(kaskoConfig);

    return {
      kaskoConfig,
      touchpointData,
    };
  }

  const touchpointData = await getTouchpoint(kaskoConfig);

  return {
    kaskoConfig,
    touchpointData,
  };
}

module.exports = getWebappData;
