/*
 * Copyright (C) 2018, 2019 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {SCThingType, SCBulkResponse, SCLicensePlate} from '@openstapps/core';
import chai, {expect} from 'chai';
import {MinimalConnector} from '../src/minimal-connector.js';
import {createUUID, executeConnector, isValidSCNamespace} from '../src/common.js';
import nock = require('nock');
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe('common', function () {
  let connector: MinimalConnector;

  beforeEach(function () {
    connector = new MinimalConnector('f-u', 'minimal-connector');
  });

  it('should be a valid SCNamespace', function () {
    const existingAddedSCLicensePlate: SCLicensePlate = 'f-u';
    const notASCLicensePlate = 'NOT-A-LICENSE';
    const existingButNotYetAddedLicensePlate: SCLicensePlate = 'a-fh';
    expect(isValidSCNamespace(existingAddedSCLicensePlate)).to.be.equal(true);
    expect(isValidSCNamespace(notASCLicensePlate)).to.be.equal(false);
    expect(isValidSCNamespace(existingButNotYetAddedLicensePlate)).to.be.equal(false);
  });

  it('should create a uuid', function () {
    const item = {
      type: 'Not even a thing',
    };
    expect(createUUID(item, 'f-u')).to.equal('3ac2b548-75d3-5326-920a-241e514fe445');
    // ID was generated once before!
  });

  it('should exectute the connector', async function () {
    const source = connector.origin;
    const backendUrl = 'http://localhost:3000';

    const bulkOpen: SCBulkResponse = {
      source: source,
      state: 'in progress',
      type: SCThingType.Message,
      uid: '744321ca-cc95-4967-b8df-42c98b792db6',
    };

    nock(backendUrl).post('/bulk').reply(200, bulkOpen);

    const nockBulkAdd = nock(backendUrl).post(`/bulk/${bulkOpen.uid}`).reply(201, {}).persist(); // otherwise consumed!

    nock(backendUrl).post(`/bulk/${bulkOpen.uid}/done`).reply(204, {});

    // should succeed
    expect(executeConnector(backendUrl, connector)).not.to.be.rejected;

    nockBulkAdd.persist(false);

    // should fail due to nockBulkAdd being consumed
    expect(executeConnector(backendUrl, connector)).to.be.rejected;
  });
});
