import rewiremock from 'rewiremock';
import '../../../mocks/electron';

import { expect } from 'chai';
import { CookieJar } from 'jsdom';
import 'mocha';
import nock from 'nock';
import { Response } from 'node-fetch';
import sinon from 'sinon';
import { fetch } from '../../../src/main/services/web-crawler';
import { storeMock } from './store.mock';

describe('Web Crawler', function() {
  this.timeout(2000);

  before(() => {
    rewiremock.enable();

    storeMock.mock.load(() => {
      return Promise.resolve(new CookieJar().serializeSync());
    });

    storeMock.mock.save(() => {
      return Promise.resolve();
    });
  });

  beforeEach(() => {
    if (!nock.isActive()) {
      nock.activate();
    }
  });

  afterEach(() => {
    nock.cleanAll();
  });

  after(() => {
    rewiremock.disable();
    storeMock.restore();
  });

  it('fetches websites', async () => {
    const callback = sinon.spy();

    const testUrl = 'https://example.com';
    nock(testUrl)
      .get(/.*/)
      .reply(
        HttpCode.OK,
        () => {
          callback();
          return JSON.stringify([{ id: 12, comment: 'Hey there' }]);
        },
        { 'Content-Type': 'application/json' }
      )
      .persist();

    const res: Response = await fetch(testUrl);
    expect(callback.callCount).to.equal(1, 'multiple requests (or none) are sent when only one should be');
    const json = await res.json();
    expect(json).to.deep.equal([{ id: 12, comment: 'Hey there' }], 'response body is incorrect');
  });
});
