import { generateTrackerLink } from '~helpers/generators';

export function getTrackerName(operator, page, path) {
  const trackerLinks = operator ? Object.keys(operator.links) : [];
  const stripTrailingSlash = (str) => (str.endsWith('/') ? str.slice(0, -1) : str);
  let trackerName = 'main';
  let tracker = '';
  for (let i = 0; i < trackerLinks.length; i += 1) {
    const trackerLink = trackerLinks[i].toLowerCase().replace(' ', '_');
    if (
      generateTrackerLink(operator, trackerLink, false, page.template) === stripTrailingSlash(path)
    ) {
      tracker =
        operator.links[
          Object.keys(operator.links).find((key) => key.toLowerCase() === trackerLink.toLowerCase())
        ];
      trackerName = trackerLink.toLowerCase();
      break;
    }

    // Not sure if this code is being used or not. To check
    if (path.includes('ppc_fallback')) {
      // eslint-disable-next-line react/prop-types
      tracker = operator.links['PPC Fallback'];
      break;
    }
    tracker = operator.links.main;
  }

  return { name: trackerName, value: tracker };
}

function isJsonString(str) {
  try {
      JSON.parse(str);
  } catch (e) {
      return false;
  }
  return true;
}

/* eslint-disable no-return-assign */
/* eslint-disable import/prefer-default-export */
export async function getAffiliateLink(operator, path, page, headers) {
  const trackerName = await getTrackerName(operator, page, path);

  const cookie =
    headers && headers.get('cookie')
      ? headers
          .get('cookie')
          .split(';')
          .map((item) => item.split('='))
          .reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {})
      : { affObject: JSON.stringify({}) };

  const urlParam = {
    site_id: process.env.SITE_ID,
    operator_short_name: operator.short_name,
    operator_type: operator.type,
    language: operator.market.split('_')[1],
    tracker_name: trackerName.name,
    market_short_code: operator.market,
    ip_address: headers ? headers.get('x-real-ip') || headers.get('host') : '127.0.0.1',
    ...(isJsonString(cookie.affObject) ? JSON.parse(cookie.affObject) : {}),
  };
  const res = await fetch(
    `${process.env.GATSBY_TRACKING_API_URL}?${new URLSearchParams(urlParam).toString()}`
  ).catch((err) => null);

  const data = res ? await res.json() : { success: false };
  return {
    props: data,
  };
}
