import * as Tracker from './tracker.mjs';

describe('Tracker Helper', () => {
  const operator = {
    short_name: 'rizk',
    type: 'sportsbook',
    market: 'ie_en',
    links: {
      main: 'testing main link',
      ppc: 'testing ppc link',
      christmas: 'testing christmas links',
    },
  };

  test('getTrackerName main/default link', () => {
    const trackerObj = Tracker.getTrackerName(operator, 'default', '/no/visit/rizk');
    expect(trackerObj.name).toEqual('main');
    expect(trackerObj.value).toEqual('testing main link');
  });

  test('getTrackerName non main/default link', () => {
    const trackerObj = Tracker.getTrackerName(operator, 'default', '/no/visit/rizk/sportsbook/ppc');
    expect(trackerObj.name).toEqual('ppc');
    expect(trackerObj.value).toEqual('testing ppc link');
  });

  test('getTrackerName non main/default link with slash', () => {
    const trackerObj = Tracker.getTrackerName(
      operator,
      'default',
      '/no/visit/rizk/sportsbook/ppc/'
    );
    expect(trackerObj.name).toEqual('ppc');
    expect(trackerObj.value).toEqual('testing ppc link');
  });

  test('getTrackerName non existent main/default link', () => {
    const trackerObj = Tracker.getTrackerName(
      operator,
      'default',
      '/no/visit/rizk/sportsbook/ppc3'
    );
    expect(trackerObj.name).toEqual('main');
    expect(trackerObj.value).toEqual('testing main link');
  });

  global.fetch = jest.fn(() =>
    Promise.resolve({
      json: () => Promise.resolve({ success: true }),
    })
  );
  beforeEach(() => {
    fetch.mockClear();
  });

  test('getAffiliateLink url params', async () => {
    await Tracker.getAffiliateLink(operator, '/no/visit/rizk', { template: 'default' }, null);

    const tracker = Tracker.getTrackerName(operator, 'default', '/no/visit/rizk');

    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: tracker.name,
      market_short_code: operator.market,
      ip_address: '127.0.0.1',
    };

    expect(fetch).toBeCalledTimes(1);
    expect(fetch).toBeCalledWith(
      `${process.env.GATSBY_TRACKING_API_URL}?${new URLSearchParams(urlParam).toString()}`
    );
  });
});
