require('dotenv').config()

const { credentialsConfig } =  require('../src/ldap/config');

process.env.PORT = process.env.TEST_PORT || 3001;
// The port is changed so that the test suite can be ran without interfering with a running server

require('../build/bundle');

const chai = require('chai');

const expect = chai.expect;

const { GraphQLClient } = require('graphql-request')

const apiEndpoint = `http://localhost:${process.env.PORT || 3001}/graphql`;

const auth = {
  username : credentialsConfig.dn.split("=")[1].split(",")[0], 
  password : credentialsConfig.passwd
};

const testList = require('./testData').testList;

describe('test server API', function () {
  
  let client;

  it('Should authentify and initialize the client', async function (){

    const tempClient = new GraphQLClient(apiEndpoint);
    const query = `
    mutation {
      login(username : "${auth.username}", password: "${auth.password}" ) 
    }
    `;

    const res = await tempClient.request(query);
    
    expect(res).to.have.property('login');

    const token = res.login;

    client = new GraphQLClient(apiEndpoint, {
      headers: {
        mode : 'cors',  // Don't know what that does, isn't necessary. Worth looking into
        credentials : 'include',  // Same
        authorization: `Bearer ${token}`
      }
    });

  });

  it('Should query all groups to test the client', async function (){
    const query = `
    query {
      allGroups {
        name
      }
    }
    `;

    const res = await client.request(query);


    expect(res).to.have.property('allGroups');
    expect(res.allGroups).to.be.an('array');
    expect(res.allGroups).to.have.lengthOf.above(3);
  });

  for(const test of testList){

    it(test.description, async function (){
      const res = await client.request(test.query);
      expect(res).to.be.deep.equal(test.result);
    });

  }

});