import { AmplitudeEvents } from '@growth-lib/amplitude-events';
import VisitOptions = Cypress.VisitOptions;
import 'cypress-iframe';
import { utilitySelector } from '@utility-lib/utility';
import { Timeouts } from '@utility-lib/constants';

const selfSellGoogleSignupSelectors = {
  signUpWithGoogleButton: '[data-testid="signUpWithGoogleButton"]',
  submitNavanAuthenticator: '[name="action"][value="accept"]'
};

export class GoogleSignUp {
  static visitGoogleSignUpPage(
    email: string,
    signupLink: string,
    asMobileDevice = false
  ): void {
    let visitOptions: Partial<VisitOptions> = {};
    if (asMobileDevice) {
      cy.viewport(400, 850);
      visitOptions = {
        onBeforeLoad: (win) => {
          Object.defineProperty(win.navigator, 'userAgent', {
            value:
              'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
          });
        }
      };
    }

    cy.visit(signupLink, visitOptions);

    AmplitudeEvents.addExpectedAmplitudeEvents('$identify', 'self signup opened');
  }

  static goToSignIUpWithGoogle(): void {
    cy.get(selfSellGoogleSignupSelectors.signUpWithGoogleButton).click();
  }

  static signUpWithGoogle(username: string, password: string): void {
    cy.allure().logStep('Signup with google');
    cy.origin(
      'https://accounts.google.com',
      {
        args: {
          username,
          password
        }
      },
      ({ username, password }) => {
        Cypress.on(
          'uncaught:exception',
          (err) =>
            !err.message.includes('ResizeObserver loop') &&
            !err.message.includes('Error in protected function')
        );

        const googleSignupSelectors = {
          googleEmail: '[id="identifierId"]',
          googlePassword: '[id="password"]',
          emailNextButton: '[id="identifierNext"]',
          passwordNextButton: '[id="passwordNext"]'
        };

        cy.get(googleSignupSelectors.googleEmail).type(username);
        cy.wait(6000);
        cy.get(googleSignupSelectors.emailNextButton).click();
        cy.wait(5000);
        cy.get(googleSignupSelectors.googlePassword).type(password);
        cy.wait(5000);
        cy.get(googleSignupSelectors.passwordNextButton).click();
        cy.wait(5000);
      }
    );
    cy.get(utilitySelector.bodySelector).then((body) => {
      if (body.find(selfSellGoogleSignupSelectors.submitNavanAuthenticator).length > 0) {
        cy.get(selfSellGoogleSignupSelectors.submitNavanAuthenticator).click();
      }
    });
  }

  static addCompanyUuidToCache(): void {
    cy.wait('@waitForOnboard').then((res) => {
      if (res.response?.body?.companyUuid) {
        cy.task('putDataInCache', {
          key: 'companyUuid',
          data: res.response?.body?.companyUuid
        });
      }
    });
  }

  static deleteUserFromAuth0(userEmail: string): void {
    let bearerToken;
    GoogleSignUp.authenticateWithAuth0().then((response) => {
      bearerToken = response.body.access_token;
      GoogleSignUp.findUserIdByEmail(bearerToken, userEmail).then((response) => {
        if (response.body.length > 0) {
          GoogleSignUp.deleteUserFromAuth0ById(
            bearerToken,
            response.body[0].user_id
          ).then(() => {
            cy.allure().logStep(`user ${userEmail} was delete from auth0`);
          });
        }
      });
    });
  }

  private static authenticateWithAuth0(): Cypress.Chainable {
    return cy.request({
      method: 'POST',
      url: `https://navan-staging-prime.us.auth0.com/oauth/token`,
      body: {
        client_id: 'DqdZKkEMfL2YyQWjQm5Z43YVcOb4g71w',
        client_secret: '-MDfKSmOt0wWdIIpP65G9L7sNDWKt-PBsSbozdIbZCVV_kgQooAmfVL4lrGskThP',
        audience: 'https://navan-staging-prime.us.auth0.com/api/v2/',
        grant_type: 'client_credentials'
      },
      retryOnStatusCodeFailure: false
    });
  }

  private static findUserIdByEmail(
    bearerToken: string,
    userEmail: string
  ): Cypress.Chainable {
    return cy.request({
      method: 'GET',
      url: `https://navan-staging-prime.us.auth0.com/api/v2/users?q=email:*${userEmail}`,
      headers: {
        Authorization: `Bearer ${bearerToken}`
      },
      retryOnStatusCodeFailure: true
    });
  }

  private static deleteUserFromAuth0ById(
    bearerToken: string,
    userId: string
  ): Cypress.Chainable {
    return cy.request({
      method: 'DELETE',
      url: `https://navan-staging-prime.us.auth0.com/api/v2/users/${encodeURIComponent(
        userId
      )}`,
      headers: {
        Authorization: `Bearer ${bearerToken}`
      },
      retryOnStatusCodeFailure: true
    });
  }
}
