/* eslint-disable no-underscore-dangle */
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;
}

function deparam(paramStr) {
  const paramArr = paramStr.split('&');
  const paramObj = {};
  paramArr.forEach((e) => {
    const param = e.split('=');
    paramObj[param[0]] = decodeURIComponent(param[1]);
  });
  return paramObj;
}

/* eslint-disable no-return-assign */
/* eslint-disable import/prefer-default-export */
export async function getAffiliateLink(operator, path, page, headers, url) {
  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({}) };

  let extraParams = null;
  if (url && url.split('?').length === 2) {
    extraParams = deparam(`${url.split('?')[1]}`);
  }

  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',
    user_agent: headers ? headers.get('user-agent') || headers.get('user-agent') : 'N/A',
    user_uuid: cookie ? cookie.affUUID || 'N/A' : 'N/A',
    facebook_browser_id: cookie ? cookie._fbp || 'N/A' : 'N/A',
    facebook_pixel_id: process.env.PIXEL_ID || 'N/A',
    ...(isJsonString(cookie.affObject) ? JSON.parse(cookie.affObject) : {}),
    ...(extraParams || {}),
  };

  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,
  };
}

export function getTrackingAPIParams(pageTemplate, module, tracker, clickedElement, url) {
  const urlParams = {};

  if (pageTemplate) {
    urlParams.page_type = pageTemplate;
  }
  if (module) {
    urlParams.module = module;
  }
  if (tracker !== 'main') {
    urlParams.tracker_name = tracker;
  }

  if (clickedElement) {
    urlParams.clicked_element = clickedElement;
  }

  if (url && url.split('?').length === 2) {
    // eslint-disable-next-line prefer-destructuring
    urlParams.request_url = url.split('?')[0];
    const extraData = deparam(url.split('?')[1]);
    if (extraData.fbclid) {
      urlParams.facebook_click_id = extraData.fbclid;
    }
    if (extraData.msclkid) {
      urlParams.microsoft_click_id = extraData.msclkid;
    }
    if (extraData.gclid) {
      urlParams.google_click_id = extraData.gclid;
    }
  } else if (url) {
    urlParams.request_url = url;
  }

  return urlParams;
}
