import { TestSupportServiceClient } from './lib';
import { loginRequest } from '../commands';
import { Logs, Random } from '@utility-lib/index';
import { HttpRequest, HttpStatusCodes } from '../base';

Cypress.Commands.add('onboardViaSupportService', () => {
  createCompanyViaTestSupportService()
    .then((companyResponse) => {
      createTravelerViaTestSupportService(companyResponse.domain, companyResponse.name);
    })
    .then((travelerResponse) =>
      loginRequest({ email: travelerResponse.email, password: travelerResponse.password })
    );
});

function createCompanyViaTestSupportService(): Cypress.Chainable<any> {
  cy.allure().logStep('Start creating brand new company via the test support service');
  const randomId = Random.randomString(12);
  const companyDomain = randomId + '-navan' + '.staging.tripactions.xyz';
  const companyName = 'TA_CYPRESS_' + randomId;
  const options = {
    method: HttpRequest.Post,
    url: Cypress.env('testSupportServiceUrl') + TestSupportServiceClient.companyUrl,
    body: {
      companyDomain: companyDomain,
      companyName: companyName
    },
    retryOnStatusCodeFailure: true
  };
  return cy
    .request(options)
    .then((xhr) => Logs.logResponseStatusAndBody(xhr))
    .then(({ body, status }) => {
      expect(status, 'Successfully created company').to.equal(HttpStatusCodes.Ok);
      return body;
    });
}

function createTravelerViaTestSupportService(
  companyDomain: string,
  companyName: string
): Cypress.Chainable<any> {
  cy.allure().logStep('Start creating traveler via the test support service');
  const options = {
    method: HttpRequest.Post,
    url: Cypress.env('testSupportServiceUrl') + TestSupportServiceClient.travelerUrl,
    body: {
      companyDomain: companyDomain,
      companyName: companyName
    },
    retryOnStatusCodeFailure: true
  };
  return cy
    .request(options)
    .then((xhr) => Logs.logResponseStatusAndBody(xhr))
    .then(({ body, status }) => {
      expect(status, 'Successfully created company').to.equal(HttpStatusCodes.Ok);
      return body;
    });
}
