import { Cache } from '../utilities/utilities';
import { HttpRequest, HttpStatusCodes } from '../utilities/api';

/**
 * Login with provided credentials and set auth token in browser local storage
 * @param email
 * @param password
 * @param isSA
 * @param localStorage
 * @returns the authentication token
 */
export function loginRequest(
  email: string,
  password: string,
  isSA = false,
  localStorage = true
): Cypress.Chainable<string> {
  cy.log(`login with ${email}`);
  return cy
    .request({
      method: HttpRequest.Post,
      url: `/api/uaa/token?isSA=${isSA}`,
      auth: { user: email, pass: password },
      retryOnStatusCodeFailure: true
    })
    .then(({ body, status }) => {
      expect(status, 'Successfully login').to.equal(HttpStatusCodes.Ok);
      const AUTH_TOKEN = 'TripActions ' + body.token;
      Cache.putDataInCache('authToken', AUTH_TOKEN);
      if (localStorage)
        window.localStorage.setItem('tripactions.TripActionsToken', body.token);
      return AUTH_TOKEN;
    });
}
